Sometimes, we want to use enum as index key type in TypeScript.
In this article, we’ll look at how to use enum as index key type in TypeScript.
How to use enum as index key type in TypeScript?
To use enum as index key type in TypeScript, we can use the in
operator.
For instance, we write
enum DialogType {
Options,
Help,
}
const openDialogs: { [key in DialogType]?: Dialog } = {
[DialogType.Options]: undefined,
};
to create the DialogType
enum.
Then we use it in a type by setting openDialogs
to the { [key in DialogType]?: Dialog }
type.
We set the index signature’s type to key in DialogType
to make sure the keys of openDialogs
must be any one of the DialogType
enum values.
Therefore, using [DialogType.Options]
as a key value wouldn’t make the TypeScript compiler raise an error.
Conclusion
To use enum as index key type in TypeScript, we can use the in
operator.