TypeScript对私有成员类型收窄时出现never类型属性不存在错误
解决TypeScript类私有成员类型收窄的never错误
错误原因
你遇到的错误是因为类型谓词this is { book: string }中声明的book是公共属性,和类的私有book属性冲突。TypeScript无法将这两个属性合并,导致交集类型被缩减为never,进而报错。
可行解决办法
方法1:调整类型谓词为基于this的交集类型
将类型谓词改为this is this & { book: string },让TypeScript识别到交集后的类型是当前类的实例,且book属性确定存在,避免私有属性冲突:
class Inventory { private book?: string; hasBook(): this is this & { book: string } { return !!this.book; } bookLength(): number | undefined { if (this.hasBook()) { return this.book.length; } else { return undefined; } } }
方法2:使用断言函数
用断言函数替代布尔返回的类型谓词,通过抛出异常的方式确保类型收窄,适合需要强制校验的场景:
class Inventory { private book?: string; assertHasBook(): asserts this is { book: string } { if (!this.book) { throw new Error("Inventory has no book"); } } bookLength(): number | undefined { try { this.assertHasBook(); return this.book.length; } catch { return undefined; } } }
方法3:直接在条件中判断私有属性
如果不需要封装判断逻辑,直接在方法内判断this.book,TypeScript能自动完成类型收窄:
class Inventory { private book?: string; bookLength(): number | undefined { if (this.book) { return this.book.length; } else { return undefined; } } }
内容的提问来源于stack exchange,提问作者guy mograbi
相关产品推荐
相关产品推荐

