首页 > 解决方案 > 使用类方法更新属性时打字稿类型缩小过于严格

问题描述

在使用类方法更新属性时,Typescript 是否应该对类型缩小如此严格?我并不是说 Typescript 应该以某种方式分析一个方法在做什么,但是通过方法修改类实例属性是一种常规做法。

我知道currentChar从普通属性或属性 getter 更改为方法可以解决这个问题,但我认为属性和 getter 非常有价值。

堆栈闪电战

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

解决方案


这是控制流分析的局限性。由于您检查了类属性,因此该属性的类型将被检查缩小,并且在调用方法时打字稿不会清除这种缩小。

您可以在此处阅读有关此内容的更多信息


推荐阅读