Skip to content
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

ts ignores type annotation and generate wrong type inference #57765

Closed
chenxinhang12345 opened this issue Mar 13, 2024 · 2 comments
Closed

ts ignores type annotation and generate wrong type inference #57765

chenxinhang12345 opened this issue Mar 13, 2024 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@chenxinhang12345
Copy link

πŸ”Ž Search Terms

wrong type inference

πŸ•— Version & Regression Information

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

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.5.0-dev.20240313#code/DYUwLgBAhgXBDOYBOBLAdgcwgHwmgrsMBALx6HADcAUAMYD2aiEARqRANoCMANAEw8AzAF0aLAHQAzekgCiUWgAsAFMtoBKUgD4IAb2oRo7AMrJ0GNepoBfK9RSTlUCAEISZAkXX7DhgPR+RijweCAAbiBIEOgQYIrBrMD0tADWBr4MTPSg4kkWUHbW1EA

πŸ’» Code

let a: string | null = null;
const b = [1,2,3];
b.forEach((c) => {
  a = String(c);
});
if(a !== null){
    // a is never in this block
    console.log(a);
}

πŸ™ Actual behavior

variable a is inferred as null in the if block, causing the variable a in the if block to be type never.

πŸ™‚ Expected behavior

a should be inferred as string

Additional information about the issue

let a: string | null = null as (string | null);
const b = [1,2,3];
b.forEach((c) => {
  a = String(c);
});
if(a !== null){
    // a is never in this block
    console.log(a);
}

This workaround magically works.

@MartinJohns
Copy link
Contributor

MartinJohns commented Mar 13, 2024

The not recognized assignment in the callback is a duplicate of #9998.

That your type annotation is not used is working as intended. Assigning a value narrows the variable. The type annotation limits what values can be assigned to it.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 13, 2024
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Mar 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants