Strongly typing props of vue components using composition api and typescript typing system

前端 未结 2 2134
臣服心动
臣服心动 2021-02-18 14:37

I am using vue composition api with typescript.

How can I strongly type the component props using typescript typing system?

2条回答
  •  佛祖请我去吃肉
    2021-02-18 15:05

    Troy Kessier's answer is not entirely accurate. I quote the documentation on definecomponent:

    Alternatively if your component does not use any option other than setup itself, you can pass the function directly […]

    So there are not two ways of declaring properties, but rather two ways of declaring a component, and each of them provides its own way of typing props.

    With the classic way and TypeScript, use PropType:

    import { defineComponent, PropType } from 'vue'
    
    export default defineComponent({
      props: {
        someOptionalString: String,
    
        someRequiredString: {
          type: String,
          required: true
        },
    
        someObject: {
          type: Object as PropType,
          required: true
        },
      },
    
      // …
    })
    

    Notice: PropType helps to give a correct TypeScript type to the props parameter in the setup function. But the underlying Vue type for the props remains Object and there is currently no way to enforce a better typing for these props passed by the parent component.

提交回复
热议问题