在 TypeScript 中将枚举结构 value:key 转换为 key:value

Convert enum structure value:key to key:value in TypeScript

我正在尝试使用此代码将枚举结构从 [key:value] 的值作为字符串转换为 [value:key] 结构。

我的错误是

Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 31 more ... | "trimEnd"' can't be used to index type 'typeof Country'.
  No index signature with a parameter of type 'number' was found on type 'typeof Country'

key as keyof Country

枚举

export enum Country {
    UnitedStates = 'US',
    Afghanistan = 'AF',
    AlandIslands = 'AX',
    }

代码

 public countries = Object.keys(Country)
  .slice(Object.keys(Country).length / 2)
  .map(key => ({
    label: key,
    key: Country[key as keyof Country],
  }));

当枚举的值为 int 时,此代码有效。

问题是您转换为错误的类型

这是一个typescript playground example

keyof Country 包含 Country 枚举对象的所有键 - 只需在示例中公开 TKeys 即可查看列表

你真正想要的是:Country[key as keyof typeof Country]
keyof typeof Country是所有枚举键的类型:"UnitedStates" | "Afghanistan" | "AlandIslands"
将鼠标悬停在示例中的 TEnumKeys 上。

要了解差异,请查看此问题: