typescript - Problém s inferenciou: „...odkazované priamo alebo nepriamo vo vlastnom inicializátore“


Dnes som problém, na ktorý som narazil, zredukoval na tento minimálny príklad. (odkaz na playground)

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
    }
}

Zdá sa, že toto je niečo, s čím by si TypeScript mal vedieť poradiť. Keď najem myšou nad nextFoo vo vscode, vyzerá to tak, že správne odvodzuje typ. Niečo ohľadom nastavenia foo na next, keď môže potenciálne byť undefined, vedie k tomuto.

Mohol by mi niekto vysvetliť, čo sa tu deje?

Odpoveď č. 1

Ako obchádzku môžete výrazne typovať vašu premennú 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
    }
}

Súvisiace články