一、枚举类型
参数 | |
---|---|
数字枚举 | enum A1 { a, b} |
字符串枚举 | enum A2 {a=“str”, b=“stri”} |
异构枚举 | |
枚举成员 | enum A4 {a, b} |
1、数字枚举
//数字枚举
enum Role {
Re1,
Re2,
Re3,
}
//默认初始值是0 如果第一个Re1是1 就默认开始递增
-
反向映射原理
//默认初始值是0 如果第一个Re1是1 就默认开始递增 //反向映射原理 var Role; (function (Role) { Role[Role["Re1"] = 0] = "Re1"; Role[Role["Re2"] = 1] = "Re2"; Role[Role["Re3"] = 2] = "Re3"; })(Role || (Role = {}));
2、字符串枚举
//字符串枚举
enum Message {
Success = "成功了",
fail = "失败了",
}
//字符串枚举不可以做为反向映射的
-
编译成JavaScript
//字符串枚举 var Message; (function (Message) { Message["Success"] = "\u6210\u529F\u4E86"; Message["fail"] = "\u5931\u8D25\u4E86"; })(Message || (Message = {}));
3、异构枚举
//异构枚举
enum Answer {
N,
Y = "yes"
}
//同时有数字和字符串 就可以构成反向映射
-
编译成JavaScript
-
反向映射原理
//异构枚举 var Answer; (function (Answer) { Answer[Answer["N"] = 0] = "N"; Answer["Y"] = "yes"; })(Answer || (Answer = {}));
4、枚举成员
-
枚举成员是只读类型 不可以被修改
-
//枚举成员 enum Char { //const a1, b2 = Char.a1, C3 = 1 + 3, D, //不需要赋初始值 //compute d4 = Math.random(), e5 = "str".length, f = 1, //需要赋初始值 } //注意在compute后面需要定义的变量需要给它赋值一个初始值
-
编译后 计算类型的 留到执行后
-
var Char; (function (Char) { //const Char[Char["a1"] = 0] = "a1"; Char[Char["b2"] = 0] = "b2"; Char[Char["C3"] = 4] = "C3"; //compute Char[Char["d4"] = Math.random()] = "d4"; Char[Char["e5"] = "str".length] = "e5"; })(Char || (Char = {}));
5、枚举类型
enum E {
a,
b,
}
enum F {
a = 0,
b = 1,
}
enum G {
a = "str",
b = "str1",
}
let e: E = 3
let f: F = 3
//不同的枚举类型 不能进行比较
//e === f 报错
let e1: E.a
let e2: E.b
//e1 === e2 不可以进行比较
let e3: E.a
//e1 === e3 可以进行比较
//只能字符的枚举 只能是自身的枚举成员
let g1: G = G.b
let g2: G.a = G.a