angular - 在 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时,此代码有效。
解决方案
问题是您转换为错误的类型
这是一个打字稿游乐场示例
keyof Country
包括 Country 枚举对象的所有键 - 只是在示例中公开TKeys
显示以查看列表
您真正想要的是:Country[key as keyof typeof Country]
keyof typeof Country
是所有枚举键的类型:示例中的"UnitedStates" | "Afghanistan" | "AlandIslands"
Hoover TEnumKeys
。
要了解区别,请查看以下问题:TypeScript 中的“keyof typeof”是什么意思?
推荐阅读
- javascript - 为什么我的图片没有出现,只看到alt?
- sql - BigQuery - “for loop like”操作,以帮助将行批量插入到表中
- tensorflow2.0 - TensorFlow 2,如何在 C++ API 中重置有状态的 RNN 隐藏状态?
- python - FLASK PYTHON ModuleNotFoundError:没有名为“tensorflow”的模块
- nginx - Istio - 用于 Azure Front Door 的默认 ssl 证书
- python-3.x - Green to python,Discord Embed 有问题
- java - 在 firestore 中使用 orderBy 执行 whereEqualTo
- go - 子包应该有自己的 go.mod 文件吗?
- openmp - OpenMP 原子比较和交换
- javascript - 有没有办法覆盖console.log报告的文件/行信息?