Vue: Typescript may be can not infer the props type

Created on 26 Oct 2017  ·  8Comments  ·  Source: vuejs/vue

Version

vue 2.5.2
typescript 2.5.3

Reproduction link

https://jsfiddle.net/chrisvfritz/50wL7mdz/typescript

Steps to reproduce

Typescript may be can not infer the props type. eg:

//App.vue
<template>
    <div>
        <vheader :test="test" :type="type"></vheader>
    </div>
</template>
<script lang="ts">
import header from './header.vue';
export default {
    components: {
        vheader: header
    },
    computed: {
    },
    methods: {
        test(left: number, right: number): number {
            return left   right;
        }
    }
}
</script>
//header.vue
<script lang="ts">
import Vue from 'vue'
export default {
    props: {
        test: Function
    },
    data() {
        this.test('aa','aa');
        return {}
    }
}
</script>

this.test('aa', 'aa') can invoke correct.
Now Vue can not get the parent's(props) function type?

What is expected?

types error.

What is actually happening?

can run success.

All 8 comments

test's type in your code is successfully inferred as Function type. That's expected behavior.
We cannot infer the actual function signature because props option does not have such information.

If you want to strict it, you need to manually annotate your props type vid PropType that would be introduced via #6856

Thanks a lot.

<script lang="ts">
import Vue from 'vue'
interface setFunction {
    (argu1: number, argu2: number):string
}
export default {
    props: {
        test: Object as (() => setFunction)
    },
    data() {
        this.test(1,1);
        return {}
    }
}
</script>

After I reference #6865, the this.test can get the correct parameter types
and I have an other question, when we use component trees, Cannot we through $props, $refs or other Vue options API to get the contextual type? such as , perhaps we can top-down or down-top to infer all the Types.

Currently, no.

  1. In any cases, typescript compiler cannot analyze template. We need to make additional type checker if we want to check it.
  2. For TSX/render function, we may be able to type check props type from a parent component. There is a discussion thread #6901

Thanks. I will learn it.

Angular's AOT Compiler can check template's type also with fullTemplateTypeCheck option.

So I think Vue's template compiler can check template's type.
@ktsn @yyx990803 May I ask you whether there is any movement to make it possible?

@ktsn That's so great job! Is it only work on vetur? Is it possible to run with Vue Cli's lint?

Yeah, I'm still sticking with Atom, even though MS bought Github and technically now owns Atom too... It's critical to have type checking in templates, I find that currently it's the main source of typos/bugs in my typescript vue apps-

Was this page helpful?
0 / 5 - 0 ratings