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

问题描述

我正在尝试使用此代码将枚举结构从 [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 悬停在上方。

要了解差异,请查看以下问题:What does “keyof typeof” mean in TypeScript?