1

求解: typescript 如何根据 enum 的字符值返回对应的 enum 实例?

 11 months ago
source link: https://www.v2ex.com/t/940015
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

求解: typescript 如何根据 enum 的字符值返回对应的 enum 实例?

  hahaFck · 6 小时 47 分钟前 · 792 次点击

比如定义以下 enum

const enum VerticalAlign {
   bottom, center, top
}

定义下面方法

//data 是后台返回的数据
function getVerticalAlign(data:JsonData):VerticalAlign {
	let value:string|null = data['vAlign'];
    switch(value) {
    	case VerticalAlign.bottom:
        	return VerticalAlign.bottom;
        ........
    }
}

现在的写法就是每个 enum 的值都要判断一次然后返回,有通用的方法返回一个 enum 的值么,直接写 VerticalAlign[value] 编译器报错.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK