Skip to content

Control flow analysis for element access with variable index doesn't account for async race conditionΒ #58822

Closed as not planned
@rixtox

Description

@rixtox

πŸ”Ž Search Terms

Control flow analysis async race condition

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.1-rc#code/IYZwngdgxgBAZgV2gFwJYHsIwOYFNkBywAtrgBQCUAXDAAoBO6xqIuAPCMvahNgHwwA3gCgYYmPXwJ6WAOQB3dPQA2AE1kBuYQF9hw0JFiIUGLHACMZdACMAVjQBKuKEtUcuPbABoYZMgA8aTm5eChgAXgEAN3RUVTCAHxgkVVw4HlxVPh8Aa1wwII9QoVFxVDhfZDAAB1x0CptbAG08sABdCPDwmAAiYyg0TB6wkXExmBcIThgIElwImGB5YFRkHHwiUkotcfFGlvy2slnSCh3xXTH91o7ulLSM1S1dYUnp1oXZbEl8T01XzDTRoLUbiA7tY5zQohbDUGAxOIlXZiN7oZS4AB0ynQ2DIAAMABK4ZTYnwAEkEJ1w2gAhHizqUxLoXgwmCxMcASWQmhYrHZcvkKD5eY0BWAKG0GUA

πŸ’» Code

async function getName(): Promise<string> {
    return 'world';
}

async function f1(obj: Record<string, ((x: string) => void) | undefined>, key: string) {
    if (typeof obj[key] === "function") {
        const name = await getName();
        obj[key](name);
    }
    obj[key] = undefined;
}

const key = 'greeting';
const obj = {
    [key](name: string): void {
        console.log(`Hello, ${name}!`);
    }
}

Promise.all([f1(obj, key), f1(obj, key)]);

πŸ™ Actual behavior

No type error, but runtime failure:

Unhandled Promise Rejection: TypeError: obj[key] is not a function. (In 'obj[key](name)', 'obj[key]' is undefined)

πŸ™‚ Expected behavior

Type checker should account for potential race condition and do not persist the narrowed type after an await statement.

Additional information about the issue

No response

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