收窄是把宽泛类型在特定分支里变精确:typeof 收窄原始类型、instanceof 收窄类实例、in 判断键存在性、判等与真值(===、&&、可选链)、可辨识联合(按字面量 tag 字段 switch)、用户自定义类型守卫 x is T。控制流分析会在赋值、return、throw 之后自动更新类型。
可辨识联合是工程上最重要的模式:{ type: 'circle', r: number } | { type: 'square', s: number },switch (shape.type) 后每个分支精确收窄,配合 never 做穷尽检查。易错点:TS 5.5 起 filter 的箭头谓词可自动推断类型谓词;断言函数 asserts x is T 用于「不满足就抛错」的场景;any 与类型断言会破坏收窄的可信度;离开作用域的闭包捕获可能使收窄失效。追问:satisfies 与 as 的差异、可辨识联合的状态机建模。
function area(s: Shape) {
switch (s.type) { case 'circle': return Math.PI * s.r ** 2; case 'square': return s.s ** 2 }
}