使用多种类型和类型化数组进行 Vuejs prop 验证

dlk*_*ulp 8 javascript typescript vue.js vuejs3

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

props: {
    prop1: {type: [String, Array], default: ""}
}
Run Code Online (Sandbox Code Playgroud)

再次查看Vetur 提交文档,看起来我应该能够设置一个数组 prop 类型,如下所示:

props: {
    prop1: {type: Array as PropType<string[]>, default: []}
}
Run Code Online (Sandbox Code Playgroud)

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

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'.
Run Code Online (Sandbox Code Playgroud)

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

Shu*_*Lin 12

这似乎有效:

props: {
    prop1: {type: [Array, String] as PropType<string[] | string>, default: ""}
}
Run Code Online (Sandbox Code Playgroud)

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