![](/img/trans.png)
[英]How can I add the value of a Typescript enum to my javascript function?
[英]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'; };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.