数组
- 类型的2种写法
let arr: number[] = [1,2,3]
let arr2: Array<number> = [1,2,3]
let arr3: Array<string | number> = [1,2,3,'4']
- 类型推断的自动更新(只发生初始值为空数组的情况)
let arr4 = [] // any
arr4.push(1) // 自动更新类型 number[]
arr4.push('2') // 自动更新类型 (string | number)[]
- 只读数组
const arr5: readonly number[] = [1,2,3]
readonly关键字不能和数组的泛型写法一起使用,使用以下写法
const arr6: ReadonlyArray<number> = [1, 2, 3]
const arr7: Readonly<number[]> = [1, 2]
const arr8 = [0,1,2] as const
- 多维数组
const arr9: number[][] = [[1,2,3], [4,5,6]]
元组
- TS特有的类型:成员类型可以自由设置的数组
const t1: [number, string] = [1, '1']
- 与数组写法上的区别
// 数组
let a: number[] = [1]
// 元组
let t: [number] = [1]
- 使用元组时必须明确给出类型,不然会被推断为数组
- 元素可选:问号只能用于元组的尾部成员,所有可选成员必须在必选成员之后
const t2: [number, string?] = [1]
- 使用扩展运算符可以表示不限数量的元组
type NamedNums = [string, ...number[]]
const t3: NamedNums = ['123',1,2,3,4,5]
- 元组的成员可以添加成员名,没有实际作用,只是用来说明每个成员的含义
type Color = [red: number, green: number, blue: number]
const c: Color = [255,255,255]
- 只读元组
type t4 = readonly[string, number]
type t5 = Readonly<[string, number]>
symbol类型
- symbol值是独一无二的
let s1: symbol = Symbol()
let s2: symbol = Symbol()
console.log(s1 === s2)
- unique symbol 表示单个值,表示这个类型的变量不能修改,只能用const声明
const s3: unique symbol = Symbol()
- 使用unique symbol声明的类型也是独一无二的
const s4: unique symbol = Symbol()
const s5: unique symbol = s4 // Type 'typeof s4' is not assignable to type 'typeof s5'