Skip to content

Misleading type hint when narrowed at declaration time #46731

Closed
@denis-sokolov

Description

@denis-sokolov

Bug Report

🔎 Search Terms

variable declaration, type hint

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs and Type System Behavior

Earliest version tested: 3.3.3333
Last version tested: 4.6.0-dev.20211105

⏯ Playground Link

Playground link with relevant code

💻 Code

type Foo = { left: string } | { right: string }

const a: Foo = { left: '' }
console.log(a.left);

🙁 Actual behavior

Type hint for const a on the line of declaration is Foo.
Type hint for const a on the line of use is { left: string }.

🙂 Expected behavior

Type hint for const a on the line of declaration is { left: string }, consistent with the type hint on the next line.

Showing the type of a as Foo is at least a visual bug. If a is Foo, how come I can access a.left on the next line?

As a more opinionated, stronger statement, I would not expect type narrowing here at all. I have very clearly annotated that a is Foo, I don't want any other type to be inferred. I have annotated it as Foo because probably in the future the value of a will be more dynamic and I want to make sure the code below supports that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions