Add functions to an Enum

后端 未结 5 1736
无人共我
无人共我 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:24

    Convert your enum to the enum pattern. I find this is a better practice in general for many languages, since otherwise you restrict encapsulation options for your type. The tendency is to switch on the enum value, when really any data or functionality that is dependent on the particular enum value should just go into each instance of the enum. I've added some more code to demonstrate.

    This might not work if you are particularly dependent on the underlying enum values. In that case you would need to add a member for the old values and convert places that need it to use the new property.

    class Mode {
       public static landscape = new Mode(1920, 1080);
       public static portrait = new Mode(1080, 1920);
    
       public get Width(): number { return this.mWidth; }
       public get Height(): number { return this.mHeight; }
    
       // private constructor if possible in a future version of TS
       constructor(
          private mWidth: number,
          private mHeight: number
       ) {
       }
    
       public GetAspectRatio() {
          return this.mWidth / this.mHeight;
       }
    }
    

提交回复
热议问题