[ 1, "message" ]
。我应该如何在TypeScript中定义它?
[ 1, "message" ]
。在 TypeScript 中定义包含多种类型的数组
使用联合类型 (string|number)[]
示例:
const foo: (string|number)[] = [ 1, "message" ];
const foo: [number, string] = [ 1, "message" ];
你甚至可以为元组成员提供有意义的名称,例如id
和text
:
const foo: [id: number, text: string] = [ 1, "message" ];
var t:[number, string] = [1, "message"]
或者
interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];
type NumberStringTuple = [number, string]
。 - basaratconst W3COLORS: [[string, string, number, number]] = [ ["aliceblue", "#f0f8ff", 240, 248, 255], ... ];
- CoderPi我的TS lint(代码检查工具)对于其他解决方案进行了投诉,所以对我有效的解决方案是:
item: Array<Type1 | Type2>
如果只有一种类型,使用如下即可:
item: Type1[]
TypeScript 3.9+ 更新 (2020年5月12日)
现在,TypeScript 还支持命名元组。这极大地提高了代码的可理解性和可维护性。请查看官方 TS Playground。
所以,现在不再使用无名称:
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.
TypeScript 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[]
。(property) 0: number (id)
而不是统一的 (property) 0: number
。因此,如果有错误消息,它将提供更多细节。 - Oleg Zarevennyi我已经确定了以下的数组类型格式,可以包含多种类型的项目。
Array<ItemType1 | ItemType2 | ItemType3>
这种格式适用于测试和类型保护。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types
但是这种格式不适合测试或类型保护:
(ItemType1 | ItemType2 | ItemType3)[]
我正在使用这个版本:
exampleArr: Array<{ id: number, msg: string}> = [
{ id: 1, msg: 'message'},
{ id: 2, msg: 'message2'}
]
这个建议有点类似于其他建议,但仍然很简单,并且相当容易记住。
如果您希望获取数字或字符串数组,您可以定义一个类型,该类型将接受数字或字符串数组。
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'.
const myarray:(TypeA | TypeB)[];
为了避免需要添加其他类型时在多个地方进行更改,最好创建类型。
type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];
[ 1, "message" ] as const ;
如果你使用 "as const",类型将会是
type const = readonly [1, "message"]
由于计算机可能的精确类型推断,这是很好的。
{ [key: string]: number | string }[]