TypeScript字符串映射枚举报错及CallErrorTypeHandler未定义求助
TypeScript枚举映射与React Native导出问题排查
第一个错误:TypeError: Cannot convert undefined value to object
这个错误的核心触发场景是当传入的errorCode为undefined或非枚举合法键的字符串时,直接用它索引枚举对象会触发类型错误。
你的代码里虽然写了mapped !== undefined的判断,但如果errorCode本身是undefined,执行CallErrorType[errorCode as keyof typeof CallErrorType]时,相当于用undefined去访问对象属性——JavaScript不允许这种操作,会直接抛出“无法将undefined转换为对象”的错误,根本走不到后续的判断逻辑。
修复方案:
先校验errorCode的合法性,确保它是有效字符串后再进行枚举映射:
const CallErrorTypeHandler = (errorCode: string | undefined, message: string) => { console.log({errorCode}); // 先拦截非法的errorCode if (!errorCode || !(errorCode in CallErrorType)) { console.error('Invalid error string:', errorCode); return; } const mapped = CallErrorType[errorCode as keyof typeof CallErrorType]; handler[mapped](message); };
第二个错误:TypeError: CallErrorTypeHandler is not a function
这个问题的原因非常直接——你没有导出CallErrorTypeHandler函数。
当前代码里CallErrorTypeHandler是局部常量,其他文件无法通过import获取到它。如果要在外部模块使用,必须添加export关键字:
export const CallErrorTypeHandler = (errorCode: string, message: string) => { // ... 原函数逻辑 };
额外注意点
你的枚举是数字枚举,TypeScript会自动生成反向映射(比如CallErrorType[0]返回"UNAUTHENTICATED"),但如果传入的errorCode是数字字符串"0",当前逻辑会找不到对应枚举值(因为CallErrorType["0"]是undefined)。如果需要支持数字字符串映射,可以补充处理逻辑:
const numCode = parseInt(errorCode, 10); if (!isNaN(numCode) && numCode in CallErrorType) { const mapped = numCode as CallErrorType; handler[mapped](message); return; }
内容的提问来源于stack exchange,提问作者Nkk
相关产品推荐
相关产品推荐

