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

如何在TypeScript中定义呢?


当前回答

[ 1, "message" ] as const ;

如果输入“as const”,则输入为

type const = readonly [1, "message"]

它的优点在于计算机可以精确地进行类型推断。

其他回答

我使用这个版本:

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

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

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

item: Array<Type1 | Type2>

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

item: Type1[]

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

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 }[]

如果你把它当作一个元组(参见语言规范的3.3.3节),那么:

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

or

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