在使用类方法更新属性时,Typescript 是否应该对类型缩小如此严格?我并不是说 Typescript 应该以某种方式分析方法在做什么,但类实例属性被方法修改是一种常规做法。
我知道将 currentChar
从普通属性或属性 getter 更改为方法可以解决此问题,但我认为属性和 getter 非常有值(value)。
export class Parser {
data = "abcdefg"
currentIndex = 0
get currentChar(): string {
return this.data[this.currentIndex]
}
nextChar(): void {
++this.currentIndex
}
}
(() => {
const parser = new Parser()
if (parser.currentChar !== "a") {
return
}
const aChar: "a" = parser.currentChar // = type 'a', value 'a'
parser.nextChar()
const bChar: "a" = parser.currentChar // = type 'a', value 'b'
if (parser.currentChar === "b") { // Error: This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.
console.log("current char really equals 'b'")
}
})();
最佳答案
这是控制流分析的局限性。由于您检查了类属性,因此检查会缩小属性的类型,并且在调用方法时 typescript 不会清除这种缩小。
您可以阅读更多相关信息 here
关于使用类方法更新属性时 Typescript 类型缩小过于严格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524794/