Composition-api: Prop validator with regular function (not arrow) breaks props inference in setup

Created on 2 Oct 2019  路  7Comments  路  Source: vuejs/composition-api

version: v0.3.2

createComponent({
  props: {
    someProp: {
      type: String,
      // using arrow function
      validator: () => true
    }
  },
  setup(props)
    // this is ok, props has correct type
  }
})
createComponent({
  props: {
    someProp: {
      type: String,
      // using regular function or shorthand method name
      // validator() {
      validator: function() {
        return true
      }
    },
  },
  setup(props) {
    // props is any
  }
})

Edit: Also, expecting argument in validator breaks type inference:

createComponent({
  props: {
    someProp: {
      type: String,
      validator: (val) => true,
    },
  },
  setup(props) {
    // props is any
  }
})
bug cantfix

Most helpful comment

@iulo Do validator: (val) => {} instead of validator(val) {}

Screen Shot 2020-03-15 at 11 42 16 PM

Screen Shot 2020-03-15 at 11 42 44 PM

All 7 comments

Seems like a TypeScript bug, can't find a workaround now.

componentProps.ts

export interface PropOptions<T = any, Required extends boolean = false> {
    type?: PropType<T> | null;
    required?: Required;
    default?: T | null | undefined | (() => T | null | undefined);
    validator?(value: any): boolean;
}

Replacing validator?(value: any): boolean; with validator?(value: T): boolean; could fix the argument issue.

@rickyruiz Hi bro, anyway fix this without change original composition-api d.ts? like Omit it in local project? Im a new ts user and this issue make me irritable

@iulo A workaround is to explicitly type the value argument of the validator function:

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

interface SomeInterface {
  foo: string
}

defineComponent({
  props: {
    someProp: {
      type: Object as PropType<SomeInterface>,
      required: true,
      validator: (value: SomeInterface) => true,
    },
  },
  setup({ val }) {
    // val is SomeInterface
  }
})

@rickyruiz still no luck. typescript version 3.8.3. Got props any

image

@iulo Do validator: (val) => {} instead of validator(val) {}

Screen Shot 2020-03-15 at 11 42 16 PM

Screen Shot 2020-03-15 at 11 42 44 PM

@rickyruiz It work! Thanks man.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lephuongbg picture lephuongbg  路  3Comments

spaceemotion picture spaceemotion  路  6Comments

ycmjason picture ycmjason  路  5Comments

zzachattack2 picture zzachattack2  路  3Comments

TooBug picture TooBug  路  6Comments