Categories
TypeScript Answers

How to use enum as a restricted key type in TypeScript?

Spread the love

Sometimes, we want to use enum as a restricted key type in TypeScript.

In this article, we’ll look at how to use enum as a restricted key type in TypeScript.

How to use enum as a restricted key type in TypeScript?

To use enum as a restricted key type in TypeScript, we can use the in keyword.

For instance, we write

enum MyEnum {
  First,
  Second,
}

let layer: { [key in MyEnum]: any };

to create the { [key in MyEnum]: any } type which restricts the keys of the object with the given type to the keys in MyEnum.

We can also make the keys optional with

let layer: { [key in MyEnum]?: any };

We put a ? after [key in MyEnum] to make the keys optional.

Conclusion

To use enum as a restricted key type in TypeScript, we can use the in keyword.

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 *