How to build a type from enum values in TypeScript?

后端 未结 3 1600
时光取名叫无心
时光取名叫无心 2021-01-17 10:53

Given the following:

enum FooKeys {
  FOO = \'foo\',
  BAR = \'bar\',
}

I\'d like to make an interface like this one, but instead of defini

3条回答
  •  無奈伤痛
    2021-01-17 11:29

    @hackape 's solution is great, but I found minimal duplication extending his solution as below:

    type ReverseMap> = {
      [V in T[keyof T]]: {
        [K in keyof T]: T[K] extends V ? K : never;
      }[keyof T];
    }
    
    const Map = {
      'FOO': "foo" as "foo",
      'BAR': "bar" as "bar",
    }
    
    const reverseMap: ReverseMap = Object.entries(Map).reduce((rMap, [k, v]) => {
      rMap[v] = k;
      return rMap;
    }, {} as any);
    
    export type Values = keyof typeof reverseMap; // 'foo' | 'bar';
    

    ReverseMap implementation is well explained here

提交回复
热议问题