程序员

Typescript 中枚举(上)

2019-02-21  本文已影响9人  zidea

可以在初始化枚举时对 Up 赋值,枚举好处是给我们一种不可以修改的集合可以用来作为配置选项,我们无法在随后动态修改

enum Direction {
    Up = 1,
    Down,
    Left,
    Right,
}

这是枚举编译后的 js 文件,

编译后的枚举

var Direction;
(function (Direction) {
    Direction[Direction["Up"] = 1] = "Up";
    Direction[Direction["Down"] = 2] = "Down";
    Direction[Direction["Left"] = 3] = "Left";
    Direction[Direction["Right"] = 4] = "Right";
})(Direction || (Direction = {}));
var Direction;
(function (Direction) {
    Direction[Direction["Up"] = 1] = "Up";
    Direction[Direction["Down"] = 2] = "Down";
    Direction[Direction["Left"] = 3] = "Left";
    Direction[Direction["Right"] = 4] = "Right";
})(Direction || (Direction = {}));
Direction.OK = 1;

console.log(Direction.Up)
console.log(Direction.OK)

我们是可以为 Direction 动态添加属性。当我们调用 Direction.Up 发生了什么?
Direction["Up"] = 1 这个不难理解

var obj = {};
// obj["Up"] = 1;
obj[obj["Up"] = 1]
console.log(obj.Up) //1
// obj["Up"] = 1;
obj[obj["Up"] = 1] = "Up"
console.log(obj.Up)
console.log(obj.Up = 1) //1
console.log(obj[1]) // Up

通过上面代码解释我们大家可能为 typescript 如何实现 enum 有所了解了吧,大家可以在自己 js 项目这样来定义您的枚举结构。

无初始化的枚举

也可以创建枚举时不给初始值

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

枚举的调用

enum Response {
    No = 0,
    Yes = 1,
}

function respond(recipient: string, message: Response): void {
    // ...
}

respond("Princess Caroline", Response.Yes)

调用枚举也很简单,就像调用对象属性一样简单。

枚举的表达式赋值

enum E{
    A = getSomeValue(),
    B // error! 'A' 是表达式初始化而不是固定值所以 'B' 需要初始化 
    }

function getSomeValue(){
    return 1;
}
enum E{
    A = getSomeValue(),
    B = getSomeValue()
    }

function getSomeValue(){
    return 1;
}
上一篇下一篇

猜你喜欢

热点阅读