TypeScript联合类型(union type)type narrowing失效问题求助
类型收窄失效的原因及解决方法
核心问题:变量未初始化
你遇到的类型收窄失效,本质是**xyz仅做了类型标注,但未初始化赋值**。在TypeScript中,未初始化的const变量(即便标注了联合类型),实际运行时值为undefined,此时TypeScript无法基于判断逻辑对其做类型收窄——因为变量本身没有持有符合联合类型的具体值。
修复示例
第一段代码修复
给变量赋予符合联合类型的具体值后,"num" in xyz的类型收窄会正常生效:
const xyz: { num: number } | { str: string } = { num: 123 }; // 初始化赋值 if ("num" in xyz) { xyz; // 类型自动收窄为 { num: number; } }
第二段代码修复
同样,初始化赋值后,基于类型判别式的收窄也会正常工作:
const xyz: { type: "num", num: number } | { type: "str", str: string } = { type: "num", num: 456 }; if (xyz.type === "num") { xyz; // 类型自动收窄为 { type: "num", num: number } }
补充场景说明
如果变量需要后续赋值而非直接初始化,可改用let声明,并确保赋值逻辑覆盖所有联合类型分支,TypeScript也能正确完成类型收窄:
let xyz: { type: "num", num: number } | { type: "str", str: string }; // 模拟后续赋值逻辑 if (Math.random() > 0.5) { xyz = { type: "num", num: 789 }; } else { xyz = { type: "str", str: "hello" }; } if (xyz.type === "num") { xyz; // 类型收窄正常生效 }
内容的提问来源于stack exchange,提问作者prmph
相关产品推荐
相关产品推荐

