Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 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 Reply

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...