TypeScript联合类型报'property does not exist on type'错误如何解决
问题原因
你遇到的是TypeScript联合类型的默认访问规则限制,并非配置错误:
- 对于联合类型
T1 | T2,TypeScript默认只允许访问两个类型共有的属性,你的Item类型没有error属性,因此直接访问item.error会触发类型报错。 - 只有当你通过类型缩小的方式,让TS明确知道当前分支里的变量属于某个具体子类型时,才能访问该子类型的独有属性。
解决方案
方案1:用in操作符做类型缩小(最简单适配现有代码)
直接修改判断条件,先判断属性是否存在于对象上,TS会自动完成类型收窄:
const item = testFunc(true); if ('error' in item) { // 此分支TS自动识别item为Error类型 console.log('error', item.error); } console.log('Happy days!', item)
方案2:定义可辨识联合(更规范的工程实践)
给每个子类型加唯一的标识字段,类型判断更可靠,尤其适合复杂联合类型:
先修改类型定义:
type Error = { type: 'error' error: string } type Item = { type: 'item' id: string name: string } type Result = Item | Error
之后判断标识字段即可:
const item = testFunc(true); if (item.type === 'error') { console.log('error', item.error); }
方案3:类型断言(不推荐,仅临时应急用)
你可以手动告诉TS变量的类型,不过这种方式跳过了TS的类型校验,类型安全度低:
if ((item as Error).error) { console.log('error'); }
内容的提问来源于stack exchange,提问作者Flo Ragossnig
相关产品推荐
相关产品推荐

