类型守卫与类型收窄
你将构建什么
一组用于 API 响应可辨识联合的类型守卫,以及一个移除 null/undefined 的泛型 isDefined 守卫。
学习目标
- 编写用户自定义类型守卫(x is T)
- 使用可辨识联合进行穷尽检查
- 用 'in' 运算符收窄
- 构建移除 null 的泛型过滤器
前置要求
- 联合类型
- 带类型谓词的函数
- 数组 filter 方法
步骤
- 1
定义可辨识联合
创建一个以 'status' 为辨识符的 API 响应类型联合:Success、Error、Loading。辨识符让编译器在 switch 语句中收窄。
代码type ApiResponse<T> = | { status: 'success'; data: T; } | { status: 'error'; message: string; } | { status: 'loading' }; function handleResponse<T>(res: ApiResponse<T>) { switch (res.status) { case 'success': return res.data; // T — narrowed case 'error': return res.message; // string — narrowed case 'loading': return 'Loading...'; // narrowed } }预期结果
每个 case 分支将 res 收窄到正确的变体 —— 无需类型转换。
- 2
编写自定义类型守卫
类型守卫是返回 'x is T' 的函数。编写 isError 检查值是否为 Error 实例,编译器将在检查后收窄。
代码function isError(x: unknown): x is Error { return x instanceof Error; } try { // ... risky code } catch (e: unknown) { if (isError(e)) { console.log(e.message); // OK — narrowed to Error } else { console.log(String(e)); } }预期结果
在 isError(e) 之后,e 被收窄为 Error,可访问 .message。
- 3
用 'in' 运算符收窄
'in' 运算符根据属性存在性收窄。编写一个守卫,通过唯一属性区分两种类型。
提示
if ('code' in error) 会收窄到拥有 code 属性的类型。
- 4
构建 isDefined 和 filterDefined
编写泛型 isDefined<T>(x: T | null | undefined): x is T 守卫,以及一个从数组中移除 null 的 filterDefined 函数。返回类型不应包含 null。
提示
Array.filter 配合类型守卫会自动收窄结果中的元素类型。
- 5
测试穷尽检查
向 ApiResponse 添加新变体并观察 handleResponse 中的编译错误 —— 穷尽检查捕获遗漏的分支。这是可辨识联合的关键安全优势。
代码// Add | { status: 'cancelled' } to ApiResponse // The switch in handleResponse now has a type error: // 'Not all code paths return a value' // This forces you to handle the new case.预期结果
添加变体会导致编译错误,直到你处理它 —— 穷尽性。
自己动手试试
function isError(x: unknown): x is Error { /* TODO */ }
function isDefined<T>(x: T | null | undefined): x is T { /* TODO */ }function isDefined<T>(x: T | null | undefined): x is T { return x != null; }
function filterDefined<T>(arr: (T | null | undefined)[]): T[] { return arr.filter(isDefined); }你学到了什么
你掌握了类型收窄 —— 让 TypeScript 拥有静态语言感觉同时保持 JavaScript 运行时灵活性的特性。可辨识联合实现了穷尽、安全的处理。
相关资源
相关课程
- 类型守卫
x is T 谓词与类型收窄。
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。