推理问题:“...在其自己的初始值设定项中直接或间接引用”

Ant*_*deo 5 type-inference typescript

我将今天遇到的问题简化为这个最小的示例。(游乐场链接

function test() {
    interface Foo<T> {
        type: 'Bar'
    }

    function nextFoo<T>(it: Foo<T>): Foo<T> {
        return it
    }

    let foo: Foo<string> | undefined = { type: 'Bar' }
    while (foo !== undefined) {
        // Type inference error here but TS has the correct inference when hovering over nextFoo
        const next = nextFoo(foo) 
        foo = next // commenting this out masks the issue
    }
}
Run Code Online (Sandbox Code Playgroud)

这似乎是 TypeScript 应该能够处理的事情。当我将鼠标悬停nextFoo在 vscode 中时,它看起来确实正确地推断出那里的类型。设置foonextwhile 它可能会undefined导致这种情况。

有人可以解释一下这是怎么回事吗?

小智 1

作为解决方法,您可以强类型化next变量:

function test() {
    interface Foo<T> {
        type: 'Bar'
    }

    function nextFoo<T>(it: Foo<T>): Foo<T> {
        return it
    }

    let foo: Foo<string> | undefined = { type: 'Bar' }
    while (foo !== undefined) {
        // Type inference error here but TS has the correct inference when hovering over nextFoo
        const next: Foo<string> | undefined = nextFoo(foo) 
        foo = next // commenting this out masks the issue
    }
}
Run Code Online (Sandbox Code Playgroud)