Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

angular - Use object literal as TypeScript enum values

I have an enum:

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

But here I'd like to use some pair of values: e.g. SMALL I would like to say that it has a key of 0 and a value of 100. I endeavor to use:

export enum PizzaSize {
  SMALL =  { key: 0, value: 100 },
  // ...
}

But TypeScript doesn't accept this one. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...