我有一个形式为:[1,"message"]的数组。
如何在TypeScript中定义呢?
我有一个形式为:[1,"message"]的数组。
如何在TypeScript中定义呢?
当前回答
const myarray:(TypeA | TypeB)[];
或者更好地避免在多个地方更改,以防您需要添加另一个类型,创建类型
type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];
其他回答
我使用这个版本:
exampleArr: Array<{ id: number, msg: string}> = [
{ id: 1, msg: 'message'},
{ id: 2, msg: 'message2'}
]
这和其他建议有点相似,但仍然很容易记住。
在TypeScript中定义多个类型的数组
使用联合类型(string|number)[] demo:
const foo: (string|number)[] = [ 1, "message" ];
我有一个形式为:[1,"message"]的数组。
如果你确定总是只有两个元素[number, string],那么你可以声明它为一个元组:
const foo: [number, string] = [ 1, "message" ];
你甚至可以为元组成员提供有意义的名字,例如id和text:
const foo: [id: number, text: string] = [ 1, "message" ];
const myarray:(TypeA | TypeB)[];
或者更好地避免在多个地方更改,以防您需要添加另一个类型,创建类型
type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];
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.
打印稿4。x+可变元组类型
TS 4.x的最后一个例子必须更改为这个:
type t = [msg: string, ...indexes: number[]];// means first element is a message and there are unknown number of indexes.
类型number更改为number[]。
更多信息请访问:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types
[ 1, "message" ] as const ;
如果输入“as const”,则输入为
type const = readonly [1, "message"]
它的优点在于计算机可以精确地进行类型推断。