TypeScript中访问错误对象属性的惯用方法是什么?
更优雅处理TypeScript中unknown类型错误的方法
在catch块里处理unknown类型的错误确实容易写出冗余代码,尤其是没法用instanceof判断的场景,下面几个方案能让代码更简洁且符合TypeScript规范:
1. 复用型类型守卫函数
把错误判断逻辑抽成一个类型守卫函数,既能复用,又能让TypeScript自动收窄类型:
function hasErrorCode(err: unknown, targetCode: string): err is { code: string } { return ( typeof err === 'object' && err !== null && 'code' in err && typeof (err as { code: unknown }).code === 'string' && (err as { code: string }).code === targetCode ); }
使用时就很清爽:
} catch (err) { if (hasErrorCode(err, "<some value>")) { console.log("Special case for this particular situation"); // 这里err已经被自动识别为{ code: string }类型,无需额外断言 } throw err; }
2. 简洁的临时判断(适合单次使用)
如果只是临时处理不想单独写函数,可以用可选链配合类型断言,比原代码简洁很多:
} catch (err) { if ((err as { code?: string })?.code === "<some value>") { console.log("Special case for this particular situation"); } throw err; }
这里用{ code?: string }断言而非any,既能简化逻辑,又保留了基本的类型约束。
3. 通用属性判断守卫
如果需要多次判断“错误是否带有code属性”,可以写一个通用的类型守卫:
function isErrorWithCode(err: unknown): err is { code: unknown } { return typeof err === 'object' && err !== null && 'code' in err; }
使用时可以进一步判断code的值:
} catch (err) { if (isErrorWithCode(err) && err.code === "<some value>") { console.log("Special case for this particular situation"); } throw err; }
上述方案都不需要用any,完全符合TypeScript的类型安全规范,同时解决了代码冗余的问题。
内容的提问来源于stack exchange,提问作者Otto
相关产品推荐
相关产品推荐

