簡體   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