实现说明
用 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));
}