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

百般思念 提交于 2020-12-02 05:06:40

问题


I am using vue composition api with typescript.

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


回答1:


As explained in the official docs you can type props in two ways:

Define arops via argument annotation

import { defineComponent } from 'vue'

export default defineComponent((props: { foo: string }) => {
  props.foo
})

Or like this

import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    foo: String
  },
  setup(props) {
    props.foo // <- type: string
  }
})



回答2:


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<MyObjectType>,
      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.



来源:https://stackoverflow.com/questions/59966387/strongly-typing-props-of-vue-components-using-composition-api-and-typescript-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!