【问题标题】:How to get enum key by value in Typescript?如何在 Typescript 中按值获取枚举键?
【发布时间】:2020-09-24 16:00:23
【问题描述】:

我有一个这样的枚举:

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

您能告诉我如何按值获取枚举键吗?即,我需要通过“BLUE COLOR”并获得“BLUE”。

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'.

【问题讨论】:

标签: typescript enums


【解决方案1】:

你可以做这样的事情来获取枚举键:

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

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

【讨论】:

  • 但我想它也有点昂贵和嘈杂。
  • 这取决于你的需要。
【解决方案2】:

如果您想通过value 获取您的enum key,那么您必须 以下列方式重新编写你的枚举:但同样的格式也可能在旧版本中工作。

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"
}

那么你可以这样得到:

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

【讨论】:

  • 当我使用 我得到以下错误:Property 'any' does not exist on type 'JSX.IntrinsicElements'.ts(2339) Type 'Element' is not assignable to type 'Colors'.ts(2322) JSX element 'any' has no corresponding closing tag.
  • 可能您已将文件作为 .jsx。它应该 .ts
  • 它可以工作,但是当我使用 时,我的反应应用程序会抛出这些错误
  • 为什么这个答案有效? any 如何启用“反向查找”?谢谢
  • 收到错误:Computed values are not permitted in an enum with string valued members.
【解决方案3】:

我正在使用这个功能

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

希望对某人有所帮助

【讨论】:

  • 我喜欢这个答案,但是如果不使用any,这个功能是否可行?
  • @AaronHill 我不知道除了any之外还有什么可以工作的
【解决方案4】:
const findMe = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];

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

【讨论】:

    【解决方案5】:

    在不使用 any 的情况下改进了 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] : '';
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 2023-03-06
      • 2020-08-09
      • 2022-08-03
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      相关资源
      最近更新 更多