When one has a Vue file:
<script>
export default {
name: 'Foo',
props: { bar: String }
}
</script>
Such templates should show error:
<foo :bar="5"></foo>
<foo :bar="myNumber"></foo>
Currently we have:
interface ComponentData<T> {
props: Record<string, any>;
on: ComponentListeners<T>;
directives: any[];
}
I'm wondering if we could do something like this. For each imported Vue component, generate its corresponding type definition such as:
interface CProp1 {
msg: string;
[other: string]: any;
}
interface ComponentData1<T> {
props: CProp1;
on: ComponentListeners<T>
directives: any[]
}
export declare const __vlsComponentHelper1: {
<T>(vm: T, tag: string, data: ComponentData1<Record<string, any>> & ThisType<T>, children: any[]): any
}
Then the virtual file with this content would complain:
__vlsComponentHelper1(this, 'foo', { props: { msg: 5 }, on: {}, directives: [] }, []) // Type 'number' is not assignable to string
It should be easy to translate the props interface:
required: false is specified, translate to msg?: type. Otherwise translate to msg: typetype is inferred from constructor types. For example String -> string. If uninferrable, use any.@ktsn What do you think?
Looks good for Vue 2. We can reuse component props type in Vue 3 as required is handled if I remember correctly.
My preferred syntax would be close to the native PropType:
props: {
userList: {
type: Array as PropType<User[]>,
default: () => []
},
category: {
type: String as PropType<MY_ENUM>,
required: true
}
}
Having to define the prop types _outside_ of the actual place you write the props, it would be less ideal in my opinion.
Also anything that stays closest to regular Vue syntax seems best for me. 馃槈
@mesqueeb We are talking about auto generated (probably virtual) type declaration for Vetur which the end users won't see / edit. I believe a simple interface type derived from Vue component's props option is enough to utlize it in template type checking.
@ktsn Aha! I had originally posted my question in the VTI feedback thread, but was redirected here...
My question was:
"Will it be possible for VTI to catch TypeScript type errors by annotating types via eg. myProp: Object as PropType<MyType>?"
Yes, it will be possible! We already have rough idea to achieve it.
Most helpful comment
Yes, it will be possible! We already have rough idea to achieve it.