I was wonder if I can use enum as an object key in interfaces.. I've built a little test for it:
export enum colorsEnum{ red,blue,green } export interface colorsInterface{ [colorsEnum.red]:boolean, [colorsEnum.blue]:boolean, [colorsEnum.green]:boolean }
When I run it I'm getting the following error:
A computed property name in an interface must directly refer to a built-in symbol.
I'm doing it wrong or it just not possible?
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
It's perfectly legal to have an enum declared inside an interface . In your situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever you use it.
Enums can also contain strings . This is more common than numeric enums, because of their readability and intent.
You can try with type:
export enum colorsEnum{ red, blue, green } export type colorsInterface = { [key in colorsEnum]: boolean; }; let example: colorsInterface = { [colorsEnum.red]: true, [colorsEnum.blue]: false, [colorsEnum.green]: true };
Or if you do not want to use all keys: add a ?
export type colorsInterface = { [key in colorsEnum]?: boolean; }; let example: colorsInterface = { [colorsEnum.red]: true, [colorsEnum.blue]: false };
OK, the key idea is to convert the Enum to the correct Type and to extends the Interface with it: You can check it out in live code here.
const enum Enum { key1 = "value1", key2 = "value2", key3 = "value3", } type EnumKeys = keyof typeof Enum; type EnumKeyFields = {[key in EnumKeys]:boolean} interface IEnumExtended extends EnumKeyFields { KeyEx1:boolean; KeyEx2:string; } // Test it const enumInstance: IEnumExtended = { };
when you inside the enumInstance
you will get autocomplete for the Enum keys and not the values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With