Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?
Posted
技术标签:
【中文标题】Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?【英文标题】:Vue.js + Typescript: How to set @Prop type to string array? 【发布时间】:2020-12-27 00:16:50 【问题描述】:将@Prop
装饰器的type
属性设置为Array<string>
的正确方法是什么?有可能吗?
我只能将它设置为Array
而没有string
,就像这样:
<script lang="ts">
import Component, Prop, Vue from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue
@Prop( type: Array, default: [] ) private readonly myProperty!: string[];
</script>
当我尝试将其更改为 Array<string>
甚至 string[]
时,我收到以下错误:
Argument of type ' type: boolean; default: never[]; ' is not assignable
to parameter of type 'PropOptions<any> | Constructor | Constructor[] | undefined'.
Types of property 'type' are incompatible. Type 'boolean' is not assignable to type
'(new (...args: string[]) => Function) | (() => any) | (new (...args: never[]) => any) | Prop<any>[] | undefined'.
这个错误信息更让我困惑:为什么现在类型被识别为boolean
?
【问题讨论】:
【参考方案1】:应该按照docs 中的说明对道具进行注释。
你应该添加as PropType<string[]>
:
<script lang="ts">
import PropType from "vue"
import Component, Prop, Vue from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue
@Prop(
type: Array as PropType<string[]>, // use PropType
default: () => [] // use a factory function
) private readonly myProperty!: string[];
</script>
默认的Array
s 和Object
s 应该总是从工厂函数返回(source)。这样可以避免(意外地)在多个组件实例之间共享一个属性。
【讨论】:
以上是关于Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?的主要内容,如果未能解决你的问题,请参考以下文章
Vue js,使用 TypeScript 从 Vue 中的表单获取数据
typescript 使用Typescript将属性添加到Vue.js中的数组
如何获得 Vue.js 2.0 类型的 TypeScript 与 Visual Studio 一起使用?
将 Typescript 与 Laravel 和 Vue.js 一起使用,导入不使其成为 Vue 组件?