Skip to content

Incorrect inferance of never type (regression in 4.3.2) #44293

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
marijnh opened this issue May 27, 2021 · 2 comments
Closed

Incorrect inferance of never type (regression in 4.3.2) #44293

marijnh opened this issue May 27, 2021 · 2 comments

Comments

@marijnh
Copy link

marijnh commented May 27, 2021

Bug Report

πŸ”Ž Search Terms

"4.3" never

πŸ•— Version & Regression Information

The code typechecks in 4.2.3, but no longer does so in 4.3.2.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export function test() {
  let found: null | string = null;
  ["hi"].forEach(s => found = s);
  if (!found) return;
  console.log(found!.length);
}

πŸ™ Actual behavior

The last line produces an error "Property 'length' does not exist on type 'never'". This goes away if the early return is removed. It seems that narrows the type of found from null to never, but that seems inappropriate in this situation (and hard to work around without any casts).

πŸ™‚ Expected behavior

I'd expect the exclamation point to be enough to make the code typecheck (as it did in previous versions).

@MartinJohns
Copy link
Contributor

MartinJohns commented May 27, 2021

This seems intentional: #44025 (comment)

this goes away if the early return is removed. It seems that narrows the type of found from null to never, but that seems inappropriate in this situation (and hard to work around without any casts).

This is a known issue as well: #9998

Due to this the type is always known as null, and never as string. So when you return TypeScript knows it's not null, but it can only ever be null, so it must be never.


A simple workaround is to avoid the inferrence of found to be null by using a type assertion:

let found: null | string = null as null | string

@marijnh
Copy link
Author

marijnh commented May 27, 2021

Seems to be a duplicate of #44025, indeed.

@marijnh marijnh closed this as completed May 27, 2021
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

No branches or pull requests

2 participants