Angular Conver枚举结构值:键到键:TypeScript中的值
我正在尝试使用此代码将枚举结构从值为字符串的[key:value]转换为[value:key]结构 我的错误是Angular Conver枚举结构值:键到键:TypeScript中的值,angular,typescript,enumerable,Angular,Typescript,Enumerable,我正在尝试使用此代码将枚举结构从值为字符串的[key:value]转换为[value:key]结构 我的错误是 Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "la
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],
}));
当enum的值为int时,此代码起作用。问题在于您转换到了错误的类型 这是一个
keyof Country
包括Country enum对象的所有键-仅在示例中显示hoover overtTKeys
,即可查看列表
您真正想要的是:Country[按键输入国家类型]
keyof typeof Country
是所有枚举键的类型:“美国”;“阿富汗”;“阿兰地”
在本例中,胡佛超过了
TEnumKeys
要了解差异,请检查以下问题: