TypeScript与JavaScript不同之处系列(六) ===>枚举

版权声明:原创文章,如想转载,请注明原文网址,注明出处;否则,禁止转载;谢谢配合! https://blog.csdn.net/c_kite/article/details/85337336

本系列目的: 列出TypeScript与JavaScript的不同点, 缩小文档内容, 提高学习速度. 原文档地址: https://www.tslang.cn/index.html

枚举

简单使用

enum Direction { a = 3, b, c, d} // 手动赋值,  b c d的值分别为4, 5, 6
enum Direction { a, b, c, d} // 默认赋值, a b c d的值分别为1, 2, 3, 4

// 使用枚举
enum Response {
    No = 0,
    Yes = 1,
}

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

respond("Princess Caroline", Response.Yes)

字符串枚举

每个成员都必须用字符串字面量,或另外一个字符串枚举成员进行初始化。

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

常量枚举

常量枚举只能使用常量枚举表达式,并且不同于常规的枚举,它们在编译阶段会被删除。 常量枚举成员在使用的地方会被内联进来。 之所以可以这么做是因为,常量枚举不允许包含计算成员。

const enum Directions {
    Up,
    Down,
    Left,
    Right
}

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]


// 编译后的的代码为: 可以看到enum没有了

var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];

异构枚举

就是字符串和数字的混合, 官方不建议这么使用

enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = "YES",
}

反向映射

enum Enum {
    A
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

猜你喜欢

转载自blog.csdn.net/c_kite/article/details/85337336