Using enum as interface key in typescript
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.
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.
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
};