Add functions to an Enum

后端 未结 5 1731
无人共我
无人共我 2020-12-23 10:55

Is it possible to add functions to an Enum type in TypeScript?

for example:

enum Mode {
    landscape,
    portrait,

    // the dream...
    toStri         


        
5条回答
  •  时光说笑
    2020-12-23 11:27

    An addition to Fenton's solution. If you want to use this enumerator in another class, you need to export both the enum and the namespace. It would look like this:

    export enum Mode {
        landscape,
        portrait
    }
    
    export namespace Mode {
        export function toString(mode: Mode): string {
            return Mode[mode];
        }
    }
    

    Then you just import the mode.enum.ts file in your class and use it.

提交回复
热议问题