Skip to content

Add utility types, ComponentProps and ComponentListeners #2094

Open
@wonderful-panda

Description

@wonderful-panda

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
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions