javascript - 我可以在 typescript 中将常用函数设置为枚举吗?

标签 javascript 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 枚举类型只是底层的映射(对象),你可以看看 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/

相关文章:

javascript - 列菜单项列表自定义

html - 如何删除垫选项填充

javascript - 在 TypeScript(Javascript) 中部分隐藏电子邮件地址

javascript - vue.js 如何将单击时的类绑定(bind)到 v-for 使用模板组件创建的列表项?

javascript - 使用 Jison 创建/翻译简单的脚本到另一种语言

javascript - 如何将 iMacros 与 Instagram 的 if/else 等逻辑一起使用?

javascript - 无法使用selenium在onclick中执行javascript

typescript - 键入两个对象以确保它们不共享任何 key

typescript - 如何使用 typescript 声明特定长度的字符串?

javascript 如果在控制台中给出 "undefined"