繁体   English   中英

我可以在打字稿中设置一个通用函数来枚举吗?

[英]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'; };

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM