Categories
TypeScript Answers

How to get enum keys as a union string type in TypeScript?

Spread the love

Sometimes, we want to get enum keys as a union string type in TypeScript.

In this article, we’ll look at how to get enum keys as a union string type in TypeScript.

How to get enum keys as a union string type in TypeScript?

To get enum keys as a union string type in TypeScript, we can use the keyof operator.

For instance, we write

enum MyEnum {
  A,
  B,
  C,
}

type enumValues = keyof typeof MyEnum;

to create the MyEnum enum.

And then we create the enumValues type with keyof typeof MyEnum; which returns the union type with the keys of MyEnum as the values.

So a variable with type enumValues can have value 'A', 'B' or 'C'.

Conclusion

To get enum keys as a union string type in TypeScript, we can use the keyof operator.

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 *