Gili Yaniv Gili Yaniv - 2 months ago 18
TypeScript Question

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?

Answer

To define an interface, the member names must be supplied not computed.

export interface colorsInterface {
    red: boolean;
    blue: boolean;
    green: boolean;
}

If you are worried about keeping the enum and the interface in sync you could use the following:

export interface colorsInterface {
    [color: number]: boolean;
}

var example: colorsInterface = {};
example[colorsEnum.red] = true;
example[colorsEnum.blue] = false;
example[colorsEnum.green] = true;

TypeScript is perfectly happy for you to pass the enum as the index and a rename-refactor would then keep everything together if you decided to rename red, for example.