TS 中支持两种枚举, 一种是 数字枚举 , 一种是 字符串枚举
数字枚举
字符串枚举
默认情况下就是数字枚举
enum Gender { Male, Female}console.log(Gender.Male);console.log(Gender.Female);
0
字面量:
enum Gender { Male = 1, Female}console.log(Gender.Male);console.log(Gender.Female);
常量,如果使用常量给前面的枚举值赋值了, 那么后面的枚举值也需要手动的赋值:
const num = 666;enum Gender { Male = num, Female = 1}console.log(Gender.Male);console.log(Gender.Female);
计算的结果,如果使用计算结果给前面的枚举值赋值了, 那么后面的枚举值也需要手动的赋值:
function getNum() { return 888;}enum Gender { Male = getNum(), Female = 1}console.log(Gender.Male);console.log(Gender.Female);
enum Gender { Male, Female}console.log(Gender.Male);
enum Gender { Male, Female}console.log(Gender[0]);
enum Gender { Male = 'www.it6666.top', Female = 'BNTang'}console.log(Gender.Male);console.log(Gender.Female);
enum Gender { Male = 'BNTang', Yao = Male}console.log(Gender.Male);console.log(Gender.Yao);
枚举中既包含数字又包含字符串, 我们就称之为 异构枚举
异构枚举
enum Gender { Male = 6, Female = 'nv'}console.log(Gender.Male);console.log(Gender.Female);
注意点:如果是字符串枚举, 那么无法通过原始值获取到枚举值:
enum Gender { Male = 6, Female = 'nv'}console.log(Gender['nv']);console.log(Gender);