How to use enum as interface key in TypeScript?

Sometimes, we want to use enum as interface key in TypeScript.

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

How to use enum as interface key in TypeScript?

To use enum as interface key in TypeScript, we can use the in operator.

For instance, we write

enum ColorsEnum {
  red,
  blue,
  green,
}

interface ColorsInterface {
  [key in ColorsEnum ]: boolean;
}

const example: ColorsInterface = {
  [ColorsEnum.red]: true,
  [ColorsEnum.blue]: false,
  [ColorsEnum.green]: true,
};

to define the ColorsInterface inteface that has [key in colorsEnum] has the keys, which restricts the key values to the ones in ColorsEnum.

Then we define the example object which use the enum values as keys.

Conclusion

To use enum as interface key in TypeScript, we can use the in operator.