特殊类型注解
枚举enum
枚举是一组有关联的常量。
反向映射
索引默认为数字,当索引都为数字时,可以通过索引值,访问到指定常量;也可以通过常量,访问到对应索引。——>反向映射
案例:
枚举中第一个元素索引默认为0,其他元素索引依次递增1,可以手动修改:
-
数字:枚举中其他元素索引按照前一位索引依次递增1(不需要手动修改,可以使用表达式)
-
字符串:其他位置元素索引也必须手动修改,其他位置索引不可以计算
含字符串值成员的枚举中不允许使用计算值。
enum Colors {
Red = 101,
Green ='123',
Blue= 1231
}; // 101 '123' 1231
enum Colors {
Red,
Green =123,
Blue
}; //0 123 124
enum Colors {
Red = '101',
Green ='123',
Blue= 1231
};
enum Colors {
Red = 10 * 10,
Green = 123,
Blue
}; //100 123 124
enum Colors {
Red = 10 * 10,
Green = '123',
Blue
}; //提示错误
编译结果案例
ts为:
enum Colors {
Red,
Green =123,
Blue
};
编译成js:
var Colors;
(function (Colors) {
Colors[Colors["Red"] = 0] = "Red";
Colors[Colors["Green"] = 123] = "Green";
Colors[Colors["Blue"] = 124] = "Blue";
})(Colors || (Colors = {}));
;
ts为:
enum Colors {
Red = '123',
Green = '456',
Blue = '789'
};
编译成js:
var Colors;
(function (Colors) {
Colors["Red"] = "123";
Colors["Green"] = "456";
Colors["Blue"] = "789";
})(Colors || (Colors = {}));
;
const+枚举
const enum Colors {
Red = '123',
Green = '456',
Blue = '789'
};
console.log(Colors['Red']);
console.log(Colors['Green']);
编译成js后,枚举不存在——>编译的性能优化
console.log("123" /* Colors['Red'] */);
console.log("456" /* Colors['Green'] */);
元组
元组
使用元组限定数组中
- 元素个数
- 元素数据类型
- 元素位置
let x: [string, number] = ['hello', 10];
特殊情况:
- 元组的可选元素
//可以把元组要限制的元素改为可选
let x1: [string, number?] = ['hello'];
let x11: [string, number?] = ['hello', 3];
- 通过rest运算符达到可选元素的作用:固定数组元素前几位,剩下元素个数不确定。
let x4: [string, ...number[]] = ['hello', 1,2,3];
- 使用元组限定的数组,不建议使用数组方法来改变数组内容。
不建议使用push unshift pop shift 修改元组
注意:数组的注解,不限制元素位置、元素个数。
当元组限定的成员是数组时,数组内元素个数不限制。
let x2: (string | number)[] = [10,'hello', 10];
//元组限定的成员是数组,数组中元素类型为number,个数不限制
let x3: [string, number[]] = ['hello', [1,2,3]];
//元组嵌套元组
let x5: [string, [number, string]] = ['hello', [1,'2']];