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 key
s 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.