我定义了一个这样的枚举:
enum VideoCategoryEnum {
knowledge = 0,
condition = 1,
interview = 2,
speech = 3,
entertainment = 4,
news = 5,
advertisement = 6,
others = 7,
}
我想为所有枚举设置一个通用函数,以便我可以执行以下操作:
VideoCategoryEnum.tostring() // 'VideoCategoryEnum'
可以这样做吗?谢谢。
最佳答案
Typescript 基本上只是构建在 Javascript 之上的编译时类型检查。 Typescript 枚举类型只是底层的映射(对象),你可以看看 this answer
因此,对枚举类型实现 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'; };
关于javascript - 我可以在 typescript 中将常用函数设置为枚举吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57601692/