【发布时间】:2021-04-01 16:55:06
【问题描述】:
使用 Vuejs 3 和 Typescript,目标是获得 string | string[] 类型的 prop。查看the docs,看起来我应该能够使用多种类型设置道具,如下所示:
props: {
prop1: {type: [String, Array], default: ""}
}
查看Vetur commit 和the 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: () => []会出现相同的错误 -
用 TS 你肯定可以做到,但是用 js idk
-
prop1: {type: [String, Array], default: (): string | string[] => ''}工作吗? -
@tao 不是真的。它使类型为
string | undefined[],这不是我想要的。
标签: javascript typescript vue.js vuejs3