【问题标题】:Vue.js + Typescript: How to set @Prop type to string array?Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?
【发布时间】: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&lt;string&gt; 甚至 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

【问题讨论】:

    标签: typescript vue.js vuejs2 typescript-typings typescript-generics


    【解决方案1】:

    应该按照docs 中的说明对道具进行注释。

    你应该添加as PropType&lt;string[]&gt;:

    <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>
    

    默认的Arrays 和Objects 应该总是从工厂函数返回(source)。这样可以避免(意外地)在多个组件实例之间共享一个属性。

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2020-03-14
      • 2017-11-13
      • 1970-01-01
      • 2020-12-11
      • 2021-12-12
      • 2020-09-02
      • 2021-06-27
      • 2021-10-27
      相关资源
      最近更新 更多