Categories
TypeScript Answers

How to use object literal as TypeScript enum values?

Spread the love

Sometimes, we want to use object literal as TypeScript enum values.

In this article, we’ll look at how to use object literal as TypeScript enum values.

How to use object literal as TypeScript enum values?

To use object literal as TypeScript enum values, we can use the enum keys to create a new object set to objects.

For instance, we write

interface PizzaInfo {
  name: string;
  cost: number;
}

enum PizzaSize {
  SMALL,
  MEDIUM,
  LARGE,
}

const pizzas: Record<PizzaSize, PizzaInfo> = {
  [PizzaSize.SMALL]: { name: "Small", cost: 100 },
  [PizzaSize.MEDIUM]: { name: "Medium", cost: 200 },
  [PizzaSize.LARGE]: { name: "Large", cost: 300 },
};

to create the pizzas object that’s set to the Record type.

The Record type lets us specify the types of keys and values of an object.

We specified that the PizzaSize enum is the type of the keys and PizzaInfo is the type for the values.

Then we can use the enum value as the keys and objects as their values.

Conclusion

To use object literal as TypeScript enum values, we can use the enum keys to create a new object set to objects.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *