`keyof` for enum names in TypeScript

Viewed 786

Given a module like:

export module Common.Enums {
  export enum Enum1 { Item = 0 }

  export enum Enum2 { Item = 0 }

  export enum Enum3 { Item = 0 }
}

I would like to define an interface with a string property restricted to the name of one of the enums, something like:

interface Test {
    enumName: keyof Common.Enums; // <<< This doesn't work, but something like that is needed
    enumName2: 'Enum1' | 'Enum2' | 'Enum3'; // <<< This does work, but is undesirable

}

However - there are a lot of enums (they get generated), so I don't want to have to hard-code 'Enum1' | 'Enum2' | 'Enum3'.

1 Answers

Common.Enums is a value that exists at runtime, not a type. To get the type of a value, you can use the typeof type query operator:

interface Test {
    enumName: keyof typeof Common.Enums;  // "Enum1" | "Enum2" | "Enum3"
}

Hope that helps; good luck!

Link to code

Related