【问题标题】:Vuejs prop validation with multiple types and typed arrays具有多种类型和类型化数组的 Vuejs 道具验证
【发布时间】:2021-04-01 16:55:06
【问题描述】:

使用 Vuejs 3 和 Typescript,目标是获得 string | string[] 类型的 prop。查看the docs,看起来我应该能够使用多种类型设置道具,如下所示:

props: {
    prop1: {type: [String, Array], default: ""}
}

查看Vetur committhe docs again,看起来我应该能够像这样设置数组道具类型:

props: {
    prop1: {type: Array as PropType<string[]>, default: []}
}

我可以让这两个单独工作没有问题,但是当我尝试将它们结合起来时,我得到一个错误:

props: {
    prop1: {type: [String, Array as PropType<string[]>], default: ""}
}

No overload matches this call.
The last overload gave the following error.
    Type '{ type: (StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]; default: string; }' is not assignable to type 'PropOptions<unknown, unknown> | (new (...args: any[]) => object) | (() => unknown) | PropConstructor<unknown>[] | null'.
    Types of property 'type' are incompatible.
        Type '(StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]' is not assignable to type 'true | (new (...args: any[]) => object) | (() => unknown) | PropConstructor<unknown>[] | null | undefined'.
        Type '(StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]' is not assignable to type 'PropConstructor<unknown>[]'.
            Type 'StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[]' is not assignable to type 'PropConstructor<unknown>'.
            Type 'PropConstructor<string[]>[]' is not assignable to type 'PropConstructor<unknown>'.
                Type 'PropConstructor<string[]>[]' is not assignable to type '() => unknown'.
                Type 'PropConstructor<string[]>[]' provides no match for the signature '(): unknown'.

我不确定用于定义类型的数组语法与直接使用PropType 之间有什么不同,但它对那里的某些东西非常不满意。我也对错误中提到的未知内容感到有些困惑,因为我希望所有内容都是字符串或数组。

【问题讨论】:

  • 默认值应该是一个返回空数组的回调
  • 这是使用type: [] 语法的必要条件吗?默认值当然可以是其他位置的纯字符串。此外,将其更改为:default: () =&gt; [] 会出现相同的错误
  • 用 TS 你肯定可以做到,但是用 js idk
  • prop1: {type: [String, Array], default: (): string | string[] =&gt; ''} 工作吗?
  • @tao 不是真的。它使类型为string | undefined[],这不是我想要的。

标签: javascript typescript vue.js vuejs3


【解决方案1】:

这似乎有效:

props: {
    prop1: {type: [Array, String] as PropType<string[] | string>, default: ""}
}

您似乎必须转换整个类型,否则您会收到警告。似乎Array 默认为uknown[] 类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多