ts枚举 enum

枚举( enum )可以定义⼀组命名常量,它能增强代码的可读性,也让代码更好维护。调用函数时传参时没有任何提示,编码者很容易写错字符串内容。并且⽤于判断逻辑的是连续且相关的⼀组值,那此时就特别适合使用枚举


//数字枚举
enum Color{
  Red,
  Green,
  Blue
}




//字符串枚举
enum Direction{
  Up = 'UP1',
  Down = 'DOWN1',
  Left = 'LEFT1',
  Right = 'RIGHT1',
}
console.log(Color[0],'Color')
console.log(Direction.Up,'up')

常量枚举

常量枚举是⼀种特殊枚举类型,它使⽤ const 关键字定义,在编译时会被内联,避免⽣成⼀些额外的代码。何为编译时内联?所谓“内联”其实就是 TypeScript 在编译时,会将枚举成员引⽤替换为它们的实际值,⽽不是⽣成额外的枚举对象。这可以减少⽣成的 JavaScript 代码量,并提⾼运⾏时性能

// 普通枚举
enum Directions {
    Up,
    Down,
    Left,
    Right
}
let x = Directions.Up;
// 编译后
"use strict";
var Directions;
(function (Directions) {
Directions[Directions["Up"] = 0] = "Up";
Directions[Directions["Down"] = 1] = "Down";
Directions[Directions["Left"] = 2] = "Left";
Directions[Directions["Right"] = 3] = "Right";
})(Directions || (Directions = {}));
let x = Directions.Up;

// 常量枚举
const enum Directions {
    Up,
    Down,
    Left,
    Right
}
let x = Directions.Up;
// 编译后
"use strict";
let x = 0 /* Directions.Up */;

上一篇:TCP/IP协议,TCP和UDP区别


下一篇:2024年最强网络安全学习路线,详细到直接上清华的教材!