- 定义数组类型的两种方式
let arr:string[] = ["1","2"]
let arr2:Array<string> = ["1","2"]
- 可以配合联合类型使用
let arr:(number | string)[]
arr3 = [1, 'b', 2, 'c']
- 定义和使用时,数组的项中不允许出现其他的类型
- 数组的一些方法的参数也会根据数组在定义时约定的类型进行限制
- 特性:限制数组元素的个数和每一项的类型
let x: [string, number];
x = ['hello', 10];
x = [10, 'hello'];
x = ['hello', 10,10];
x[2]
- 可解构,若解构个数越界,则报错
const tuple: [string, number] = ['musi', 2]
const [name, id] = tuple
- 可使用 Rest 参数
type RestTupleType = [number, ...string[]];
let restTuple: RestTupleType = [666, "Semlinker", "Kakuqo", "Lolo"];
- 可通过
?
声明元素可选
let tuple: [string, boolean?]
tuple = ['musi', true]
tuple = ['musi']
- 添加 readonly 关键字,定义其为只读元组
const tuple: readonly [string] = ['musi']
tuple[0] = 'kingmusi'
tuple.push('kingmusi')