使用类方法更新属性时 Typescript 类型缩小过于严格

标签 typescript

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

我知道将 currentChar 从普通属性或属性 getter 更改为方法可以解决此问题,但我认为属性和 getter 非常有值(value)。

Stackblitz

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/

相关文章:

typescript - Typescript 接口(interface)通常存储在应用程序中的什么位置?

javascript - Angular2 JSON 返回

注入(inject) spy 时出现 Angular TestBed.inject 类型错误

angularjs - ngx-toastr GlobalConfig 超时设置

typescript - 从另一个 TypeScript 包导入 TypeScript 类型

Angular 2 Http.get 没有响应

javascript - 在 TSX 文件 : Property 'createRef' does not exist on type 'typeof React'

arrays - RxJS 从 typescript 中的静态数组创建新的 Observable "Array"

angular - 失败 : Unexpected directive 'ContactDetailsComponent' imported by the module 'DynamicTestModule' . 请添加@NgModule 注解

javascript - Angular2变量 'Undefined'外部方法