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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.