Skip to content

Possibly undefined type is not correctly detected in async codeΒ #58148

@schrodit

Description

@schrodit

πŸ”Ž Search Terms

"undefined check async"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "undefined", "async"

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.4#code/C4TwDgpgBAYg9nKBeKBvAUFLUBuBDAGwFcIAuKAZ2ACcBLAOwHMAadAX3XQGMC8KKoAFQhU0nbFDB18waADME5IvQAmEOQwgqoAH1gJkUZWo30tAbk6ZsYIgCMCtLlD4h6zlXADKcALYRgAAsGRgAKAEoxCQkg2goAOgVEFAxotNxCEnIAcjxs1nSoNktrNJoQKMLsPAB3PFpgKDMaqAAFaj84iFDQ6kikAD5KAMFafzgiYF7mKABWAAZ58PDLQrYoU0ICCtSqrC44ego4Agh4gjgw7KT8qFiEpPj8YggV0qr7xIMUY3VNFVW6Q4Eg471sDicRiOAQilTKwQe3yhJn+gKwHFBoVc7igsMGcKgByOjUaKGaQhEUze7yJojAhmA8U8Pn8sSYETRd3iygoMPC71q9UaYEsbHCEXQQA

πŸ’» Code

type Foo = {
    value: string,
}

class Test {

    private foo: undefined | Foo = undefined;


    public async doSomething() {
        this.foo = {
            value: 'a',
        };

        try {
            await new Promise((r) => setTimeout(r, 500));
        } finally {
            console.log('foo', this.foo.value);
            this.foo = undefined;
        }
    }

    public unset() {
        this.foo = undefined;
    }
}

(async () => {
    const t = new Test();

    const p = t.doSomething();
    t.unset()
    await p;
})()

πŸ™ Actual behavior

Typescript compiles without errors.
Running the code throws TypeError: Cannot read properties of undefined (reading 'value')

πŸ™‚ Expected behavior

Typescript should throw an error that this.foo might be undefined.

Additional information about the issue

Typescript successfully detects that this.foo can be undefined before the assignment in the function.

But it seems to not take into account that the value might change when executed async.

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