Microsoft/TypeScript
GitHub ã§èŠãParentheses in nullish coalescing chains impacts type narrowing
Open
#44,988 opened on 2021幎7æ12æ¥
BugDomain: check: Control FlowHelp Wanted
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
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
getResult1throws a type error, as TypeScript incorrectly infers thatvalue2.bhas a type ofstring | undefined.getResult2does not throw a type error, as TypeScript correctly infers thatvalue2.bhas a type ofstring.
ð 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.