gee*_*eko 28 strong-typing typescript vue.js vue-composition-api
我正在使用带有打字稿的 vue 组合 api。
如何使用打字稿打字系统对组件道具进行强类型输入?
Pal*_*leo 41
Troy Kessier 的回答并不完全准确。我引用了以下文档definecomponent:
或者,如果您的组件不使用设置本身以外的任何选项,您可以直接传递函数 […]
所以没有两种声明属性的方式,而是两种声明组件的方式,每种方式都提供了自己的输入 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
},
},
// …
})
Run Code Online (Sandbox Code Playgroud)
注意:PropType有助于为函数中的props参数提供正确的 TypeScript 类型setup。但是 props 的底层 Vue 类型仍然Object存在,目前没有办法为父组件传递的这些 props 强制执行更好的类型。
小智 6
正如官方文档中所解释的,您可以通过两种方式输入 props:
通过参数注释定义 arops
import { defineComponent } from 'vue'
export default defineComponent((props: { foo: string }) => {
props.foo
})
Run Code Online (Sandbox Code Playgroud)
或者像这样
import { defineComponent } from 'vue'
export default defineComponent({
props: {
foo: String
},
setup(props) {
props.foo // <- type: string
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11736 次 |
| 最近记录: |