类型 Guard
一句话解释
类型 guard 是检查 (如 typeof or 用户-定义函数) 那个 narrows 值's 类型在内 conditional 块, 启用类型-safe access 到类型-特定属性.
用大白话说
A type guard is a runtime check that tells TypeScript to narrow a type. After the check passes, TypeScript knows the value is a more specific type, and lets you access type-specific properties.
Built-in type guards include typeof (for primitives), instanceof (for classes), and in (for property existence). You can also write user-defined type guards using the x 是 T predicate.
For example, if 值 is 字符串 | 数字, you can't call 值.toUpperCase() directly. But inside 如果 (typeof 值 === "字符串"), TypeScript narrows value to 字符串 and the call is allowed.
示例
typescript
// Built-in type guard with typeof
function process(x: string | number) {
if (typeof x === "string") {
return x.toUpperCase(); // x narrowed to string
}
return x.toFixed(2); // x narrowed to number
}
// User-defined type guard
function isString(x: unknown): x is string {
return typeof x === "string";
}typeof narrows x in 每个分支. '是' predicate 创建用户-定义 guard.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。