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'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…