Skip to content

Generic inference seems broken when optional chaining is involved #35104

@michalburger1

Description

@michalburger1

TypeScript Version: 3.7.2

Search Terms: generic inference optional chaining

Code

interface Base {
    doBaseStuff(): void
}

interface Derived extends Base {
    doDerivedStuff(): void
}

function a<T extends Base>(arg: T | undefined): T {
    if (arg === undefined) {
        throw new Error('It was undefined')
    }
    return arg
}

function f(arg?: { foo: Derived }): Derived {
    return a(arg?.foo)
    // Note that the following is completely okay:
    // return a(arg?.foo as Derived | undefined)
}

Expected behavior: T is inferred to be Derived and type checking passes

Actual behavior: T is inferred to be Base and type checking fails

Playground Link: http://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgEJwM4oN4ChkHIAmA9ulgMpgCuMMAFAJQBcyAbicEbgL666hIsRCgAi0YGwhFkEAB6QQRDGkw58hUuKiTpVWgxbtO3PrhjUQCMMBIhkcADwAVWQohKV5CAD56cKABzVlcAH2RLIggYUGkjVzxCZGAYZH8g5ABebIilaNiiRmREpMIwAAsoEgB3ZBAIWoBRKCqoegBySPz6onbGDQI+JKgIGih7AMDefgsrGztkBkmAflZsRZISVm1dGR4jHakZEoIRsYn0wOWAOhhN-p4gA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions