Description
What problem does this feature solve?
Get type checking for function passed as prop to a component.
Currently, it is possible to use PropType
to get better typing on props passed to a component.
For example:
import Vue, { PropType } from "vue";
interface User {
name: string;
}
export default Vue.extend({
name: "MyComponent",
props: {
user: Object as PropType<User>
}
});
In this example, the user
prop will be correctly typed by the TypeScript type checker.
This however doesn't work with function props, the following example...
import Vue, { PropType } from "vue";
interface User {
name: string;
}
type ConfirmCallback = (confirm: boolean) => void;
export default Vue.extend({
name: "MyComponent",
props: {
user: Object as PropType<User>,
confirmCallback: Function as PropType<ConfirmCallback>
}
});
... yields the following error:
src/MyComponent.ts:13:22 - error TS2352: Conversion of type 'FunctionConstructor' to type 'PropType<ConfirmCallback>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'FunctionConstructor' is not comparable to type '() => ConfirmCallback'.
13 confirmCallback: Function as PropType<ConfirmCallback>
What does the proposed API look like?
As converting to unknown
first is somewhat unwieldy (and seems not to work in a SFC Vetur setup, maybe this should be looked into separately), it would be nice to have a helper function exposed by Vue such as the following...
import { PropType } from "vue";
export default function TypedFunctionProp<T>(): PropType<T> {
return (Function as unknown) as PropType<T>;
}
... which would allow writing the following:
import Vue, { PropType, TypedFunctionProp } from "vue";
interface User {
name: string;
}
type ConfirmCallback = (confirm: boolean) => void;
export default Vue.extend({
name: "MyComponent",
props: {
user: Object as PropType<User>,
confirmCallback: TypedFunctionProp<ConfirmCallback>()
}
});
I would be willing to write a PR for this, but I'm not sure where to put the definition of the TypedFunctionProp
function as it can't be put in the declaration file.
I'm also completely open to having a different name for that function. Maybe FunctionPropType
is more consistent. I've actually switched to FnPropType
in the project I'm working on, as it's relatively short, and is consistent with the PropType
name.