Skip to content

Type inference ignores explicit type annotationΒ #55330

Closed
@belyakov-am

Description

@belyakov-am

πŸ”Ž Search Terms

type inference
explicit type
narrowing
type annotation

πŸ•— Version & Regression Information

TS version 5.1.6

⏯ Playground Link

https://www.typescriptlang.org/play?#code/IYZwngdgxgBAZgV2gFwJYHsI1JKBBEEVAcwgFsBTCZACggC4YIEyAjCgJwEpGAFD9GVQgKAHmZtOAPhgBvAFAwlMADYVkMZBQAeyRiGQdUEYjAA+TBCpUwAvJesBueYuUQKAdxj9BwijRoOChB0FQA3Ci47GQVlOM0dDXsAchDKBN1k53jlIJDw-yQAEwo4YwoirlclAF8q6uwPYFQNdy8fIREAvNCIqNsZEWQAFVRKdARaHoKAGhgARgAGZcWuLmcG1DgYGi1dO1t7Zmso2JyYIOQEDixFhpqXOMvrrD3kADo1E2QAC2caoA

πŸ’» Code

async function asyncAssignment(n: number): Promise<number> {
    let text: string | null = null;

    new Promise((resolve) => {
        text = 'some text';
        resolve(undefined)
    })

    await new Promise((resolve) => setTimeout(resolve, 10000));

    if (text === null) {
        return 0
    }

    return text.length;
}

πŸ™ Actual behavior

Typescript narrows text type to null and not to string | null

πŸ™‚ Expected behavior

Expecting to have string | null type for text before explicit type narrowing (if (text === null)) and string type after explicit type narrowing

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