Skip to content

Wrong error "TS2532: Object is possibly 'undefined'" after assigning to const with optional chaining #40201

Closed
@ssypi

Description

@ssypi

TypeScript Version: 4.1.0-dev.20200823 also tested with 4.0.2

Search Terms:
TS2532
Object is possibly 'undefined'
Code

interface Foo {
    foo: string;
    bar: string;
}

export default function getBar(obj: Foo | undefined): string {
    const foo = obj?.foo;
    if (!foo) {
        throw new Error("Invalid args");
    }

    return obj.bar; // <--- obj is possible undefined here according to tsc even though it can never really be
}

Expected behavior:

No typescript error should be shown here, because 'obj' can never be undefined since 'foo' would then also be undefined so the code would never reach the final return.

Actual behavior:
with --strictNullChecks
TS2532: Object is possibly 'undefined' at the final return line for 'obj'

Playground Link:
Playground Link
Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions