【问题标题】:Convert enum structure value:key to key:value in TypeScript在 TypeScript 中将枚举结构 value:key 转换为 key:value
【发布时间】:2021-05-26 12:26:06
【问题描述】:

我正在尝试使用此代码将枚举结构从 [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 时,此代码有效。

【问题讨论】:

    标签: angular typescript enumerable


    【解决方案1】:

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

    这是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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 2016-02-29
      • 2018-01-20
      • 2023-01-03
      • 2018-07-07
      • 2013-06-27
      • 1970-01-01
      相关资源
      最近更新 更多