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?
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
An enum is a data type that can be created by a Java programmer to represent a small collection of possible values. Technically, an enum is a class and its possible values are objects.
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.
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'
If you need to use Type, try adding some code. usage: getPizzSizeSpec(PizzaSize.small).value
enum PizzaSize { small, medium, large } interface PizzaSizeSpec { key: number, value: number } function getPizzaSizeSpec(pizzaSize: PizzaSize): PizzaSizeSpec { switch (pizzaSize) { case PizzaSize.small: return {key:0, value: 25}; case PizzaSize.medium: return {key:0, value: 35}; case PizzaSize.large: return {key:0, value: 50}; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With