Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ssypi opened this issue Aug 23, 2020 · 1 comment · Fixed by #44730

Comments

@ssypi
Copy link

ssypi commented Aug 23, 2020

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:

@ssypi
Copy link
Author

ssypi commented Aug 23, 2020

Oops I think this is a duplicate of #39996 which itself was deemed a duplicate of an old issue #12184

Sorry, don' know how I missed that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant