Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum as interface key in typescript

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?

like image 475
Gili Yaniv Avatar asked Sep 26 '16 11:09

Gili Yaniv


People also ask

Can I use enum in interface TypeScript?

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.

Can I use enum as a type in TypeScript?

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.

Can we declare enum in interface?

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.

Can enum be string TypeScript?

Enums can also contain strings . This is more common than numeric enums, because of their readability and intent.


2 Answers

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 }; 
like image 115
Yan Q Avatar answered Sep 22 '22 17:09

Yan Q


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.

like image 38
Nisim Joseph Avatar answered Sep 21 '22 17:09

Nisim Joseph