赋值后类型收窄丢失
快速摘要
你在 if 块中收窄了类型,但赋值给变量后收窄丢失 —— 变量具有宽类型。
为什么发生
收窄的值被赋值给以更宽类型声明的变量,丢失收窄
收窄和使用之间的函数调用导致 TypeScript 将类型放宽回去
收窄基于属性检查但对象被重新赋值,使收窄无效
最小示例
✗ 错误代码
let value: string | number = getValue();
if (typeof value === 'string') {
// value is string here
const stored = value; // string
}
console.log(value.toUpperCase()); // error: value is string | number✓ 修复代码
let value: string | number = getValue();
if (typeof value === 'string') {
console.log(value.toUpperCase()); // safe: narrowed to string
}
// Or use a type guard:
function isString(x: unknown): x is string { return typeof x === 'string'; }
if (isString(value)) { console.log(value.toUpperCase()); } // narrowed在 if 块内使用收窄的值保持类型收窄有效,或类型谓词函数在调用间保留收窄。
如何诊断
悬停赋值后的变量查看类型是否被放宽回去
检查收窄和使用之间是否有函数调用可能使收窄无效
使用返回类型谓词的类型守卫函数在赋值间维护收窄
如何修复
使用类型谓词函数(x is string)维护收窄:function isString(x: any): x is string
将收窄的值赋给带显式收窄类型注解的新变量
将使用收窄类型的代码移到收窄仍有效的 if 块内
如何预防
使用带类型谓词的类型守卫函数实现可在赋值间存活的可重用收窄
将收窄代码保留在收窄块内而非提取到更宽类型的变量
相关资源
相关术语
相关课程
- 类型收窄
学习类型收窄。