TypeScript-数组类型
小开开 2020-12-08 17:16:00 2020-12-08 221 0
数组类型
数组类型的语法为:
T[]
其中 T
可以是任何类型,代表的是数组的元素类型
let list: number[] = [1, 2, 3];// 二维数组let vec: number[][] = [[1, 2, 3], [1, 2, 3]];
元组类型
元组和数组类似,只不过元组是一种固定长度的数组,每个元素有自己的类型。元组(Tuple)的语法为:
[T0, T1, ...]
T0, T1
代表任意类型,省略号表示可以有任意多个元素。
// 声明一个元组,包含两个元素,第一个元素为string类型,第二个元素为number类型let x: [string, number];// 正确x = ['hello', 10];// 错误;元素类型不匹配// error TS2322: Type 'number' is not assignable to type 'string'// error TS2322: Type 'string' is not assignable to type 'number'x = [10, 'hello'];// 错误;长度不匹配// error TS2741: Property '1' is missing in type '[string]' but required in type '[string, number]'x = ['hello'];
- 作者:joye
- 出处:https://github.com/joye61