Use object literal as TypeScript enum values

前端 未结 6 1310
星月不相逢
星月不相逢 2020-12-29 17:54

I have an enum:

export enum PizzaSize {
  SMALL =  0,
  MEDIUM = 1,
  LARGE = 2
}

But here I\'d like t

6条回答
  •  鱼传尺愫
    2020-12-29 18:23

    TypeScript supports numeric or string-based enums only, so you have to emulate object enums with a class (which will allow you to use it as a type in a function declaration):

    export class PizzaSize {
      static readonly SMALL  = new PizzaSize('SMALL', 'A small pizza');
      static readonly MEDIUM = new PizzaSize('MEDIUM', 'A medium pizza');
      static readonly LARGE  = new PizzaSize('LARGE', 'A large pizza');
    
      // private to disallow creating other instances of this type
      private constructor(private readonly key: string, public readonly value: any) {
      }
    
      toString() {
        return this.key;
      }
    }
    

    then you can use the predefined instances to access their value:

    const mediumVal = PizzaSize.MEDIUM.value;
    

    or whatever other property/property type you may want to define in a PizzaSize.

    and thanks to the toString() overriding, you will also be able to print the enum name/key implicitly from the object:

    console.log(PizzaSize.MEDIUM);  // prints 'MEDIUM'
    

提交回复
热议问题