← 中文资源

简体中文版本

用 asserts 断言函数收窄类型

返回类型为 asserts value is T 的断言函数在入口处校验形状:不合法直接抛 TypeError,通过之后调用方变量自动收窄,守卫逻辑集中在一处复用。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ada@example.com
rejected: profile.email must be a string

实现说明

用 asserts 断言函数收窄类型的核心是函数 assertProfile、render。 代码拒绝在坏状态上继续,在守卫处直接抛出 TypeError。

使用要点

  • 守卫 typeof value !== 'object' || value === null 成立时借助提前的 throw 直接离开。
  • 跑完文件,输出里会留下标记——rejected:。

常见问题

这个示例会以什么方式失败?

代码会抛出 TypeError——守卫条件 typeof value !== 'object' || value === null 会在主逻辑之前拦下坏状态。请在调用点处理,或有意让它向上传播。

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 assertProfile、render。

主要签名是 function assertProfile(value: unknown)

核心语句

throw new TypeError('profile.email must be a string');
throw new TypeError('profile must be an object');
return raw.email.toLowerCase();

代码示例

// Assertion function: a return type of asserts value is T narrows the caller
interface Profile {
  email: string;
}

function assertProfile(value: unknown): asserts value is Profile {
  if (typeof value !== 'object' || value === null) {
    throw new TypeError('profile must be an object');
  }
  if (typeof (value as Record<string, unknown>).email !== 'string') {
    throw new TypeError('profile.email must be a string');
  }
}

function render(raw: unknown): string {
  assertProfile(raw);
  // 从这里开始 raw 已收窄为 Profile,直接访问字段不再报错
  return raw.email.toLowerCase();
}

console.log(render({ email: 'Ada@Example.com' }));

try {
  render({ email: 42 });
} catch (error) {
  console.log('rejected:', error instanceof TypeError ? error.message : String(error));
}