TypeScript数组和元组

数组

定义数组的两种方式

1. []

let list: number[] = [1, 2, 3];

2. 数组泛型,Array<元素类型>

let list: Array<number> = [1, 2, 3];

 

 

元组Tunple

元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。

let x: [string, number];
x = ['hello', 10]; // 正确
x = [10, 'hello']; // 错误

 

当访问一个已知索引的元素,会得到正确的类型

console.log(x[0].substr(1)); // ok
console.log(x[1].substr(1)); // error, 'number' does not have 'substr'

当访问一个越界的元素,会使用联合类型替代

x[3] = 'world'; // ok, 字符串可以赋值给(string | number)类型
console.log(x[5].toString()); // ok, 'string'和'number'都有toString
x[6] = true; // error, 布尔不是(string | number)类型

联合类型是高级主题,后面讨论。

 

 

参考:https://www.tslang.cn/docs/handbook/basic-types.html

 

posted on 2020-08-21 10:46  白小鸽  阅读(1028)  评论(0编辑  收藏  举报