首页 > 解决方案 > 在 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'

键作为国家的键

枚举

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时,此代码有效。

标签: angulartypescriptenumerable

解决方案


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

这是一个打字稿游乐场示例

keyof Country包括 Country 枚举对象的所有键 - 只是在示例中公开TKeys显示以查看列表

您真正想要的是:Country[key as keyof typeof Country]
keyof typeof Country是所有枚举键的类型:示例中的"UnitedStates" | "Afghanistan" | "AlandIslands"
Hoover TEnumKeys

要了解区别,请查看以下问题:TypeScript 中的“keyof typeof”是什么意思?


推荐阅读