简体   繁体   中英

How to get enum key by value in Typescript?

I have an enum like this:

export enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

Could you let me know how to get enum key by value please? ie, I need to pass "BLUE COLOR" and get 'BLUE'.

Colors["BLUE COLOR"] gives error Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'. Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'.

If you want to get your enum key by value in that case you have to re write your enum in following manners: But same format also might be work in older version as well.

For Vanilla Js it should be like below:

 enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

For.tsx it should be like below:

 enum Colors {
        RED = "RED COLOR" as any,
        BLUE = "BLUE COLOR" as any,
        GREEN = "GREEN COLOR" as any
    }

For.ts it should be like below:

enum Colors {
  RED = <any>"RED COLOR",
  BLUE = <any>"BLUE COLOR",
  GREEN = <any>"GREEN COLOR"
}

Then you can get like this way:

Retrieve enum key by value:

let enumKey = Colors["BLUE COLOR"];
    console.log(enumKey);

Output:

在此处输入图像描述

Another way: Retrieve enum key by value:

let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];

console.log(enumKey);

Output:

在此处输入图像描述

Test on jsfiddle:

Coding sample on jsfiddle

const findMe = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];

https://jsfiddle.net/anniebbird/agy3unfk/3/

I am using this function

export function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
  let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
  return keys.length > 0 ? keys[0] : '';
}

Tests with jest

describe('enum', () => {
  enum TestEnumWithNumber {
    ZERO
  }

  enum TestEnumWithString {
    ZERO = 'ZERO'
  }

  it('should return correct key when enum has number values', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithNumber, TestEnumWithNumber.ZERO);
    expect(key).toBe('ZERO');
  });

  it('should return correct key when enum has string values', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithString, TestEnumWithString.ZERO);
    expect(key).toBe('ZERO');
  });

  it('should return correct key by passing corresponding string value', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithString, 'ZERO');
    expect(key).toBe('ZERO');
  });
});

Hope it helps someone

Improved getEnumKeyByEnumValue without using any :

 export function getEnumKeyByEnumValue< TEnumKey extends string, TEnumVal extends string | number >(myEnum: { [key in TEnumKey]: TEnumVal }, enumValue: TEnumVal): string { const keys = (Object.keys(myEnum) as TEnumKey[]).filter( (x) => myEnum[x] === enumValue, ); return keys.length > 0? keys[0]: ''; }

Cast the string directly and it will give you the key you want.

let enumKey = "BLUE COLOR" as Colors; 

You can do something like this fetching the enum keys:

enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

for (let item in Colors) { 
    if (Colors[item] === "BLUE COLOR") { 
        alert(item)
    }
}

try like this

enum Colors
{
   RED = "RED COLOR",
   BLUE = "BLUE COLOR",
   GREEN = "GREEN COLOR"
};   

 console.log(Object.keys(Colors)[Object.values(Colors).indexOf('BLUE COLOR' as unknown as Colors)]);

Improved getEnumKeyByEnumValue by adding type checks:

enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

type ValueOf<T> = T[keyof T];

function getEnumKeyByEnumValue<R extends (string | number), T extends {[key: string] : R}>(myEnum: T, enumValue: ValueOf<T>): string {
  let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
  return keys.length > 0 ? keys[0] : '';
}



let enumKey = getEnumKeyByEnumValue(Colors, Colors.RED);

// next line will trigger: Argument of type '"OTHER COLOR"' is not assignable to parameter of type 'ValueOf<typeof Colors>'.
//let enumKey = getEnumKeyByEnumValue(Colors, "OTHER COLOR");

console.log(enumKey);

https://jsfiddle.net/2ry1u8qb/

I'd like to fix the code a little:

return Object.keys(myEnum).find(x => myEnum[x] === enumValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM