【发布时间】:2020-05-14 21:49:42
【问题描述】:
我正在使用带有 typescript 的 vue composition api。
如何使用打字稿打字系统强输入组件道具?
【问题讨论】:
标签: typescript vue.js strong-typing vue-composition-api
我正在使用带有 typescript 的 vue composition api。
如何使用打字稿打字系统强输入组件道具?
【问题讨论】:
标签: typescript vue.js strong-typing vue-composition-api
Troy Kessier 的回答并不完全准确。我引用the documentation on definecomponent:
或者,如果您的组件不使用除 setup 本身以外的任何选项,您可以直接传递函数 […]
所以没有两种声明属性的方式,而是两种声明组件的方式,并且每种方式都提供了自己的 props 类型。
使用经典方式和TypeScript,使用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
},
},
// …
})
注意:PropType 有助于为 setup 函数中的 props 参数提供正确的 TypeScript 类型。但是 props 的底层 Vue 类型仍然是 Object,目前没有办法为父组件传递的这些 props 强制执行更好的类型。
【讨论】:
正如官方docs 中解释的那样,您可以通过两种方式输入道具:
通过参数注释定义 arops
import { defineComponent } from 'vue'
export default defineComponent((props: { foo: string }) => {
props.foo
})
或者像这样
import { defineComponent } from 'vue'
export default defineComponent({
props: {
foo: String
},
setup(props) {
props.foo // <- type: string
}
})
【讨论】: