vuejs / composition-api

Composition API plugin for Vue 2
https://composition-api.vuejs.org/
MIT License
4.19k stars 343 forks source link

setup function provide a wrong prop type,when use type: Function #971

Closed workkk98 closed 1 year ago

workkk98 commented 1 year ago

Dependencies

vue version: 2.6.14 @vue/composition-api: 1.7.1(latest)

background

we all know vue2.x prop check support Function. image

like this case,Function type infer to never

import { defineComponent, onBeforeMount } from '@vue/composition-api'

export default defineComponent({
  props: {
    handler: {
      type: Function,
      required: true
    }
  },
  setup(props) {
    onBeforeMount(() => {
      // ts tell me handler type is never, but actually it is a function
      props.handler()
    })
  }
})
workkk98 commented 1 year ago

this case can explain by next link.It seems to ExtractFunctionPropType type cause this case.So maybe we should rewrite ExtractFunctionPropType like this.

declare type ExtractFunctionPropType2<T extends Function, TArgs extends Array<any> = any[], TResult = any> = T extends (...args: TArgs) => TResult ? T :  T extends Function ? (...args: any[]) => any : never;

ts playground

workkk98 commented 1 year ago

or we should add a union type in inferPropType like this.

type InferPropType<T> = T extends null
  ? any // null & true would fail to infer
  : T extends { type: null | true }
    ? any // As TS issue https://github.com/Microsoft/TypeScript/issues/14829 // somehow `ObjectConstructor` when inferred from { (): T } becomes `any` // `BooleanConstructor` when inferred from PropConstructor(with PropMethod) becomes `Boolean`
    : T extends ObjectConstructor | { type: ObjectConstructor }
      ? Record<string, any>
      : T extends BooleanConstructor | { type: BooleanConstructor }
        ? boolean
          : T extends DateConstructor | { type: DateConstructor}
            ? Date
              : T extends FunctionConstructor | { type: FunctionConstructor }
                ? Function
                : T extends Prop<infer V, infer D>
                  ? unknown extends V
                    ? D extends null | undefined
                      ? V
                      : D
                    : ExtractCorrectPropType<V>
                  : T
github-actions[bot] commented 1 year ago

Stale issue message