如何在Typescript中按值获取枚举键?

nkkqxpd9  于 2023-01-31  发布在  TypeScript
关注(0)|答案(9)|浏览(734)

我有一个如下的枚举:

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

你能让我知道如何通过值得到枚举键吗?也就是说,我需要传递“蓝色”并得到“蓝色”。
Colors["BLUE COLOR"]给出错误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'.

uoifb46i

uoifb46i1#

如果你想通过value得到你的enum key,你必须用下面的方式重写你的枚举:但同样的格式也可能在旧版本中工作。

一米二米一x

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

一米三米一x

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

一米四米一x

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

那么你可以这样得到:

一米五米一x

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

一米六米一x

一米七米一x

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

console.log(enumKey);

一米八米一x

一米九米一x

Coding sample on jsfiddle

注:25th August上发布了新公告,请注意。Have alook here

8iwquhpp

8iwquhpp2#

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

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

h43kikqp

h43kikqp3#

我正在使用此函数

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] : '';
}

玩笑测试

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');
  });
});

希望能帮到什么人

webghufk

webghufk4#

改进了 getEnumKeyByEnumValue,但未使用任何

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] : '';
}
bweufnob

bweufnob5#

像这样尝试

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)]);
fv2wmkja

fv2wmkja6#

直接转换字符串,它会给予你想要的键。

let enumKey = "BLUE COLOR" as Colors;
yhuiod9q

yhuiod9q7#

您可以执行类似下面的操作来获取枚举键:

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

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

tsm1rwdh8#

通过添加类型检查改进了getEnumKeyByEnumValue:

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/

6za6bjd0

6za6bjd09#

我想稍微修改一下代码:

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

相关问题