Add functions to an Enum

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

    can make enum like by private constructor and static get return object

    export class HomeSlideEnum{
    
      public static get friendList(): HomeSlideEnum {
    
        return new HomeSlideEnum(0, "friendList");
    
      }
      public static getByOrdinal(ordinal){
        switch(ordinal){
          case 0:
    
            return HomeSlideEnum.friendList;
        }
      }
    
      public ordinal:number;
      public key:string;
      private constructor(ordinal, key){
    
        this.ordinal = ordinal;
        this.key = key;
      }
    
    
      public getTitle(){
        switch(this.ordinal){
          case 0:
    
            return "Friend List"
          default :
            return "DChat"
        }
      }
    
    }
    

    then later can use like this

    HomeSlideEnum.friendList.getTitle();
    

提交回复
热议问题