Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

TypeScript中enum枚举类型的实现原理?

ts中的代码:

// 数字枚举
enum PostStatus {
  Draft = 0,
  baidu = 1,
  sougou = 2,
}

上述编译为js代码:

var PostStatus;
(function (PostStatus) {
    PostStatus[PostStatus["Draft"] = 0] = "Draft";
    PostStatus[PostStatus["baidu"] = 1] = "baidu";
    PostStatus[PostStatus["sougou"] = 2] = "sougou";
})(PostStatus || (PostStatus = {}));

将js代码放入浏览器执行,得到这样的结果:
image
上述的js代码是怎么运行出来PostStatus这样的对象的?

{0: "Draft", 1: "baidu", 2: "sougou", Draft: 0, baidu: 1, sougou: 2}

对上述js代码的执行顺序不是很明白,求解答,十分感谢。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
PostStatus[PostStatus["Draft"] = 0] = "Draft";

可以分解成

PostStatus["Draft"] = 0;   //{Draft:0}
PostStatus[PostStatus["Draft"]]="Draft"   //{Draft:0,0:"Draft"}

所以typescript的enum其实是定义了一个双向的映射关系
这样可以通过枚举值获取到枚举名称

var name=PostStatus[0];

通过枚举名称获取到枚举值

var value=PostStatus["Draft"];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...