You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何标注TypeScript断言函数签名,实现参数类型自动收窄?

TypeScript 断言函数实现异常类型自动收窄

你需要用TypeScript的**断言函数(Assertion Function)**语法标注assertMyError,让编译器识别出:只要函数正常返回,传入的参数就一定是MyError类型。

修改后的实现代码

class MyError extends Error {
  public constructor(public code: string, message?: string) {
    super(message)
    // 修复原型链,避免部分环境下instanceof判断异常(可选但建议)
    Object.setPrototypeOf(this, MyError.prototype)
  }
}

/** 若参数不是MyError实例则重新抛出 */
function assertMyError(e: unknown): asserts e is MyError {
  if (!(e instanceof MyError)) {
    throw e
  }
}

declare function downloadFile(name: string): void;

try {
  downloadFile("hello")
} catch (e) {
  assertMyError(e)
  // 此时TypeScript会自动将e识别为MyError类型,可直接访问code属性
  console.log(e.code)
}

方案说明

  • 断言函数的asserts e is MyError标注,会告诉TypeScript:如果函数没有抛出异常,那么e的类型必然是MyError,无需额外的if判断就能直接使用MyError的属性。
  • 相比返回布尔值的类型谓词函数,这种写法完全贴合你封装类型检查、消除冗余判断的需求。

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:30:55