javascript - 我可以在 TypeScript 中为枚举设置一个公共函数吗?
我已经这样定义了一个枚举:
enum VideoCategoryEnum {
knowledge = 0,
condition = 1,
interview = 2,
speech = 3,
entertainment = 4,
news = 5,
advertisement = 6,
others = 7,
}
我想为所有枚举设置一个公共函数,这样我就可以这样做:
VideoCategoryEnum.tostring() // 'VideoCategoryEnum'
这有可能做到吗?谢谢。
答案#1
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'; };
答案#2
ts-nameof 应该能满足你的需求。
如果你使用 Babel,有几个选项,如果使用 tsc,则有一个选项。
在你上面的例子中,它只是这样使用的:
enum VideoCategoryEnum {
knowledge = 0,
condition = 1,
interview = 2,
speech = 3,
entertainment = 4,
news = 5,
advertisement = 6,
others = 7,
}
nameof(VideoCategoryEnum); // VideoCategoryEnum
