将TypeScript中的enum结构值:key转换为key:value
将TypeScript中的enum结构值:key转换为key:value
我正在尝试用下面的代码将一个枚举结构从[value: key]的形式转换为[key: value]的形式,其中值是字符串。
我的错误是:
因为类型为'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 31 more ... | "trimEnd"'的表达式不能用于索引类型为'Country'的'typeof'。 在'typeof Country'上找不到具有'type 'number'的参数的索引签名。
key as keyof 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], }));
当枚举的值为整数时,这段代码可以工作。
问题出现的原因是类型转换错误。在代码中,将值转换为错误的类型。应该将值转换为正确的类型。
解决方法是将值转换为正确的类型。在示例代码中,应该使用Country[key as keyof typeof Country]
来获取正确的类型。其中keyof typeof Country
表示枚举的所有键的类型,而keyof Country
表示Country枚举对象的所有键。可以通过将鼠标悬停在示例中的TKeys
和TEnumKeys
上来查看它们的类型。
要理解这两者之间的区别,可以参考这个问题:What does “keyof typeof” mean in TypeScript?