TypeScript中如何通过字符串获取数字枚举并解决类型报错
TypeScript数字枚举的两个常见问题解决:字符串转枚举值、遍历枚举的类型错误
一、通过字符串获取对应的枚举值
TypeScript数字枚举会自动生成正向(键→值)映射,直接用枚举的键名字符串作为索引就能拿到对应值。如果能确保输入字符串是枚举的有效键,可直接使用:
const operationStr = "DEFEND"; const operationValue = OperationType[operationStr as keyof typeof OperationType];
如果需要处理可能的无效字符串,可添加类型守卫做校验:
function isOperationTypeKey(str: string): str is keyof typeof OperationType { return str in OperationType; } const operationStr = "DEFEND"; if (isOperationTypeKey(operationStr)) { const operationValue = OperationType[operationStr]; // 此处operationValue会被正确推断为OperationType类型 }
二、修复遍历枚举时的类型错误
原代码中Object.keys(OperationType)返回的是string[],TypeScript无法确认这些字符串是枚举的有效键,因此报错。可通过以下两种方式修复:
方式1:类型断言为枚举键类型
将过滤后的数组断言为枚举键类型数组,让TypeScript识别value是枚举的合法键:
(Object.keys(OperationType).filter((v) => isNaN(Number(v))) as (keyof typeof OperationType)[]).map((value) => { return <MenuOption onSelect={() => setOperationType(OperationType[value])} text={value} /> })
方式2:用类型守卫过滤元素
写一个类型守卫函数,确保过滤后的元素是枚举的键,TypeScript会自动推断正确类型:
function isOperationTypeKey(str: string): str is keyof typeof OperationType { return str in OperationType && isNaN(Number(str)); } Object.keys(OperationType).filter(isOperationTypeKey).map((value) => { return <MenuOption onSelect={() => setOperationType(OperationType[value])} text={value} /> })
这种方式比类型断言更严谨,能避免把枚举反向映射生成的数值字符串(比如"1"、"20")误当成枚举键。
内容的提问来源于stack exchange,提问作者CyberMew
相关产品推荐
相关产品推荐

