letv5: 1 | 2 | 3 = 4// 报错:Type '4' is not assignable to type '3 | 1 | 2'. (4不能赋值给1|2|3类型的值)
5. 数组、元祖、枚举等
数组
约束数组的数据类型,有两种写法,和一种默认推断写法
1 2 3 4 5 6 7 8
// 默认推断写法 let arr = [1, 3, '3', null] // 根据类型推断arr的类型为 (number | string | null)[] 可以存储 数字、字符串、null类型的值的数组 // 类型约束方式1 letarr1: number[] = [1, 2, 3] arr1.push('abc') // 报错:Argument of type 'string' is not assignable to parameter of type 'number'.(‘string’类型的参数不能赋值给‘number’类型的参数。) // 类型约束方式2 letarr2: Array<number | string> = [1, 3, '3'] arr2.push(null) // 报错:Argument of type 'null' is not assignable to parameter of type 'string | number'.(“Null”类型的参数不能分配给“string | number”类型的参数。)
元组
TypeScript中还提供了类似于数组的结构 —— 元组
元组中的数据量是固定的,也就是长度是固定的,并且每一个位置的数据类型也是被约束的
1 2 3 4 5 6 7 8
letaaa: [number, string, number] = [1, 'abc', 2] aaa[0] = 'A'// 报错:Type 'string' is not assignable to type 'number' 类型
letbbb: [number] = [1, 2] // Type '[number, number]' is not assignable to type '[number]'. Source has 2 element(s) but target allows only 1. (类型“[number, number]”不能赋值给类型“[number]”。源有2个元素,但目标只允许1个。)
枚举
enum 关键字声明枚举,枚举相当于一个常量对象
默认设置
1 2 3 4 5 6 7 8 9
// 默认设置 enumMyEnum { A, B, C } // 默认声明的时候对应的是一个数组的形态,从0开始绑定值 console.log(MyEnum.A) // 0 console.log(MyEnum.B) // 1 console.log(MyEnum.C) // 2 console.log(MyEnum[0]) // "A" console.log(MyEnum[2]) // "B" console.log(MyEnum[3]) // "C"
letxiaohong: Person = { name: "小红", ago: 20, // 报错:Object literal may only specify known properties, and 'ago' does not exist in type 'Person'.(对象字面值可能只指定已知属性,“ago”在“Person”类型中不存在。) gender: 0 }
letxiaoxue: Person = { name: "小雪", age: 20, gender: "女"// 报错:Type 'string' is not assignable to type '0 | 1'.(仅支持0|1) }