![](/img/trans.png)
[英]Vue.js + Typescript: How to set @Prop type to string array?
[英]How to set vue prop type to Array of User Class using typescript?
我想知道是否有办法让我的组件只接受 User 类的数组。
@Prop({ required: true, type: () => Array }) readonly user: Array<User>;
上面的代码接受所有数组。
可以使用自定义验证器检查道具类型:
@Prop({
required: true,
validator: prop => Array.isArray(prop) && prop.every(item => item instanceof User)
}) readonly user: Array<User>;
TypeScript 是结构类型化的, Array<User>
不需要数组作为User
类的实例。
Array<User>
的目的是在组件内部断言 prop 类型,最好应该是readonly user!: Array<User>
。
由于 vue-class-component 和 vue-property-decorator 类组件的限制,TypeScript 在编译时无法保证 props 的类型安全。 Vue 组合 API 可用于严格类型的 TypeScript 组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.