在TypeScript中定义多个类型的数组

我有一个形式为:[ 1, "message" ]的数组。

如何在TypeScript中定义呢?

247940 次浏览

在TypeScript中定义多个类型的数组

使用联合类型(string|number)[]演示:

const foo: (string|number)[] = [ 1, "message" ];

我有一个数组的形式:[1,"message"]。

如果你确定[number, string]总是只有两个元素,那么你可以将它声明为元组:

const foo: [number, string] = [ 1, "message" ];

重要提示

对于具有不同属性的复杂类型,当您希望访问仅在其中一个类型上可用的属性时,这将不起作用。

请看这个更新的答案

如果你将它作为元组处理(参见语言规范的3.3.3节),那么:

var t:[number, string] = [1, "message"]

interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];

我的TS lint抱怨其他解决方案,所以解决方案是为我工作:

item: Array<Type1 | Type2>

如果只有一种类型,可以使用:

item: Type1[]

我使用这个版本:

exampleArr: Array<{ id: number, msg: string}> = [
{ id: 1, msg: 'message'},
{ id: 2, msg: 'message2'}
]

这和其他建议有点相似,但仍然很容易记住。

我已经确定了以下格式,用于输入可以具有多种类型项的数组。

Array<ItemType1 | ItemType2 | ItemType3>

这可以很好地用于测试和类型保护。https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

这种格式不适用于测试或类型保护:

(ItemType1 | ItemType2 | ItemType3)[]

如果您对获取数字或字符串的数组感兴趣,则可以定义一个类型,该类型将接受数字或字符串的数组

type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]

如果你期望一个特定顺序的数组(即数字和字符串)

type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.

TypeScript 3.9+更新(2020年5月12日)

现在,TypeScript也支持< >强命名的元组< / >强。这大大增加了代码的可理解性可维护性查看官方TS游乐场。


所以,现在不再是未命名的:

const a: [number, string] = [ 1, "message" ];

我们可以添加名字:

const b: [id: number, message: string] = [ 1, "message" ];

请注意:你需要一次添加所有的名字,你不能省略一些名字,例如:

type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.

提示:如果你不确定最后一个元素的计数,你可以这样写:

type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.

如果在一个对象中处理具有多个值类型的数组,这对我来说是有效的。

 { [key: string]: number | string }[]

请注意,@basarat所接受的答案将不适用于注释中@seawave23所述的复杂类型,当你试图访问属性时,TypeScript会报错

当您希望访问仅在其中一种类型上可用的属性时,它将不适用于具有不同属性的复杂类型。

const myarray:(TypeA | TypeB)[];

或者更好地避免在多个地方更改,以防您需要添加另一个类型,创建类型

type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];