元组(Tuple)的各元素的类型不必相同,但赋值时元素类型的顺序必须与元组定义时的类型顺序一致,且元素数量也必须一致:
let data: [string, number] = ['hello', 2022];//正确
let data: [string, number] = [ 2022,'hello'];//元素类型不一致,错误
let data: [string, number] = ['hello'];//元素数量不一致,错误
可以通过索引访问元组元素,可以通过push向元组中增加元素,但不可以访问定义元组时不存在的索引,但可以通过for遍历到所有元素,这是一个非常奇怪的设计,建议不要使用push方法
let data: [string, number] = ['hello', 2022];//正确
console.log(data[0]);//输出'hello'
data[0] = 'hi';
console.log(data[0]);//输出'hi'
data.push('good luck');
console.log(data);//输出[ 'hi', 2022, 'good luck' ]
console.log(data.length);//输出3
console.log(data[2]);//输出error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'
for(let i of data)
{
console.log(i);//依次输出hi 2022 good luck
}
可以定义可选元素,可选元素即使没有赋值,也可以通过索引读取及设置
let hello: [string, number?, string?] = ['hello', 2022]
console.log(hello);//输出[ 'hello', 2022 ]
console.log(hello[2]);//输出undefined
console.log(hello.length);//输出2
hello[2] = 'good luck';
console.log(hello);//输出[ 'hello', 2022, 'good luck' ]
console.log(hello.length);//输出3