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



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

my error is

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

enumeral

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],
}));

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

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

这是一个typescript playground的例子

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

您实际需要的是:Country[key as keyof typeof Country]
keyof typeof Country是所有enum键的类型:"UnitedStates" | "Afghanistan" | "AlandIslands"
Hoover overTEnumKeys

要理解它们的区别,看看这个问题:" keyof typeof "在TypeScript中是什么意思?

最新更新