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

Parentheses in nullish coalescing chains impacts type narrowing #44988

Open
joealden opened this issue Jul 12, 2021 · 1 comment
Open

Parentheses in nullish coalescing chains impacts type narrowing #44988

joealden opened this issue Jul 12, 2021 · 1 comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@joealden
Copy link

Bug Report

🔎 Search Terms

nullish coalescing chain parentheses type narrowing prettier

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about nullish coalescing. Note that at the time of writing, 4.3.5 was the latest stable release.

⏯ Playground Link

Playground link with relevant code

💻 Code

type T =
  | { a: string; b: string }
  | { a: string; b?: undefined }
  | { a?: undefined; b: string };

const getResult1 = (value1: string | undefined, value2: T): string => {
  return value1 ?? value2.a ?? value2.b;
};

const getResult2 = (value1: string | undefined, value2: T): string => {
  return value1 ?? (value2.a ?? value2.b);
};

🙁 Actual behavior

  • getResult1 throws a type error, as TypeScript incorrectly infers that value2.b has a type of string | undefined.
  • getResult2 does not throw a type error, as TypeScript correctly infers that value2.b has a type of string.

🙂 Expected behavior

The existence and placement of parentheses in nullish coalescing chains should not impact type narrowing, as to my knowledge (and prettier, as it automatically removes the parentheses seen in getResult2), x ?? y ?? z and x ?? (y ?? z) actually behave the same at runtime.

@joealden joealden changed the title Parentheses in Nullish Coalescing Chains Impact Type Narrowing Parentheses in nullish coalescing chains impact type narrowing Jul 12, 2021
@joealden joealden changed the title Parentheses in nullish coalescing chains impact type narrowing Parentheses in nullish coalescing chains impacts type narrowing Jul 12, 2021
@MartinJohns
Copy link
Contributor

Related: #42203

Narrowings only occur on predefined syntactic patterns, [...]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants