我有一个形式为:[1,"message"]的数组。
如何在TypeScript中定义呢?
我有一个形式为:[1,"message"]的数组。
如何在TypeScript中定义呢?
当前回答
如果您对获取数字或字符串的数组感兴趣,则可以定义一个类型,该类型将接受数字或字符串的数组
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'.
其他回答
如果您对获取数字或字符串的数组感兴趣,则可以定义一个类型,该类型将接受数字或字符串的数组
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'.
如果在一个对象中处理具有多个值类型的数组,这对我来说是有效的。
{ [key: string]: number | string }[]
在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" ];
我已经确定了以下格式,用于输入可以具有多种类型项的数组。
阵列望远镜< 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'}
]
这和其他建议有点相似,但仍然很容易记住。