自定义类型 Guards in TypeScript
编写用户-定义类型 guard 函数使用 'x 是类型' predicate for 自定义 narrowing.
你将学到
- 什么类型 predicate (x 是类型) 是 and 如何它 工作
- 编写自定义类型 guard 函数 for 复杂类型
- Using in 运算符 as inline 类型 guard
- 组合类型 guards 使用 discriminated unions
概念讲解
Type Predicates
A type guard is a function that returns a boolean and tells the compiler the narrowed type. You declare it with a type predicate: 函数 isString(x: unknown): x 是 字符串. The x 是 字符串 part is the predicate — it means "如果这个函数返回真, x 是字符串". After calling isString(值) in an if block, TypeScript narrows 值 to 字符串 inside that block, just like a typeof check.
Why Custom Type Guards
Built-in narrowing (typeof, instanceof, in) only covers simple cases. For complex types — like discriminated unions, branded types, or runtime-validated shapes — you need custom guards. For example, isApiError(响应) can check whether a response object has an 错误 field and narrow the type accordingly. Custom guards make narrowing reusable and readable.
The in Operator
The in operator checks for property presence and acts as an inline type guard: 如果 ("name" in obj) narrows obj to a type that has name. This is useful for distinguishing object shapes without a discriminant field. Combined with type predicates, the in operator lets you build sophisticated runtime checks that the compiler understands and uses for narrowing.
示例代码
// Custom type guard with a type predicate.
function isString(value: unknown): value is string {
return typeof value === "string";
}
// Type guard for a discriminated union.
type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Pet = Fish | Bird;
function isFish(pet: Pet): pet is Fish {
return (pet as Fish).swim !== undefined;
}
// Type guard using the 'in' operator inline.
function move(pet: Pet): void {
if ("swim" in pet) {
pet.swim();
} else {
pet.fly();
}
}
// Using the custom guard.
function process(value: unknown): string {
if (isString(value)) {
// value is narrowed to string here.
return value.toUpperCase();
}
return "not a string";
}
console.log(process("hello"));
console.log(process(42));
类型 predicates (x 是类型) turn 布尔值函数到 narrowing tools. Use 它们 for 复杂类型那个 typeof and instanceof cannot handle. in 运算符 narrows based on 属性 presence.
动手试一试
- JSON Validator
类型 guards 验证 JSON shapes at 运行时 — 测试你的 validation logic.
- JSON Schema Validator
JSON Schema validation mirrors 类型 guard logic for API 数据.
常见错误
错误写法
编写类型 predicate 那个做 不 actually 验证类型 at 运行时
正确做法
predicate (x 是类型) 是 claim. 函数请求体必须 actually 检查类型. 错误 guard gives 假 confidence — 总是验证运行时检查 matches claimed 类型.
错误写法
Using 类型 assertions (as) 相反的 类型 guards for narrowing
正确做法
Assertions bypass 检查. 类型 guards 验证 at 运行时 and narrow safely. Use guards 当类型是 genuinely uncertain, 特别是 for unknown or 任何值.
练习 自定义类型 Guards in TypeScript
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。