Add utility types, ComponentProps and ComponentListeners
What problem does this feature solve?
Make it easy to write component in TypeScript.
What does the proposed API look like?
ComponentProps
Extract props type from component. Equivalent to React's ComponentProps.
const MyComp1 = defineComponent({
props: {
foo: { type: String, required: true },
bar: Number
}
})
const MyComp2 = defineComponent({
props: ['foo', 'bar']
})
const MyComp3 = (props: { text: string }) => (<div>{props.text}</div>)
// { foo: string, bar?: number }
type MyComp1Type = ComponentProps<typeof MyComp1>
// { foo?: any, bar?: any }
type MyComp2Type = ComponentProps<typeof MyComp2>
// { text: string }
type MyComp3Type = ComponentProps<typeof MyComp3>
ComponentListeners
Extract event handlers type from component.
const MyComp1 = defineComponent({
emits: {
input: (value: string) => true,
click: (x: number, y: number) => true
}
})
const MyComp2 = defineComponent({
emits: ['input', 'click']
})
// { input: (value: string) => void, click: (x: number, y: number) => void }
type MyComp1Listeners = ComponentListeners<typeof MyComp1>
// { input: (...args: any[]) => void, click: (...args: any[]) => void }
type MyComp2Listeners = ComponentListeners<typeof MyComp2>
Usecases
Writing wrapper component
const MyComp = defineComponent({
props: { foo: String, bar: Number, baz: Boolean }
})
type MyCompProps = ComponentProps<typeof MyComp>
const WrappedMyComp = (props: Omit<MyCompProps, 'foo'>)=> h(MyComp, { foo: 'FooValue', ...props })
Writing event handlers safely
const MyComp = defineComponent({
emits: {
input: (value: string) => true,
click: (x: number, y: number) => true
}
})
type MyCompListeners = ComponentListeners<typeof MyComp>
const Parent = defineComponent({
components: { MyComp },
setup() {
const onClick: MyCompListeners['click'] = (x, y) => {
...
}
const onInput: MyCompListeners['input'] = value => {
...
}
return { onClick, onInput }
}
})
Improve JSX typing (by template literal types of TS4.1)
// transform { foo: T1, bar: T2 } to { onFoo?: T1, onBar?: T2 }
type On<T> = {
[K in keyof T & string as `on${capitalize K}`]?: T[K]
}
declare global {
namespace JSX {
// Make enable to use onXxx as component attributes
type LibraryManagedAttributes<C, P> = C extends new () => infer V
? (V extends { $props: infer P } ? P : {}) & On<ComponentListeners<C>>
: P
}
}
@wonderful-panda I see you started working on this in your fork. Do you need any help to get this ready for a PR?
@LinusBorg PR is already opened.