![](/img/trans.png)
[英]How can I add the value of a Typescript enum to my javascript function?
[英]Can I set a common function to enum in typescript?
我已经定义了一个这样的枚举:
enum VideoCategoryEnum {
knowledge = 0,
condition = 1,
interview = 2,
speech = 3,
entertainment = 4,
news = 5,
advertisement = 6,
others = 7,
}
我想为所有枚举设置一个通用函数,以便可以执行以下操作:
VideoCategoryEnum.tostring() // 'VideoCategoryEnum'
是否有可能做到这一点? 谢谢。
Typescript基本上只是基于Javascript构建的编译时类型检查。 Typescript枚举类型只是引擎盖下的地图(对象),您可以看一下此答案
因此,将toString
函数实现为枚举类型非常简单。 您可以在定义枚举类型之后执行此操作。 只要确保您不要将实现放在.d.ts
文件中,因为这些文件不会被编译为javascript代码。
根据上面的答案链接,您的枚举类型将被编译为:
var VideoCategoryEnum;
(function (VideoCategoryEnum) {
VideoCategoryEnum[VideoCategoryEnum["knowledge"] = 0] = "knowledge";
VideoCategoryEnum[VideoCategoryEnum["condition"] = 1] = "condition";
// ...
})(VideoCategoryEnum || (VideoCategoryEnum = {}));
;
/* would equivalent to the following:
VideoCategoryEnum = {
"knowledge": 0,
"condition": 1,
...
"0": "knowledge",
"1": "condition",
}
*/
// since it's just basically an object, you can do whatever you want with it like below
// your implementation of toString
VideoCategoryEnum.toString = function() { return 'VideoCategoryEnum'; };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.