Closed as not planned
Description
Bug Report
if (a.b?.c ?? false) a.b.c
does not narrow the type of a.b
to remove nullish types.
🔎 Search Terms
conditional type narrowing, nullish coalescing operator
🕗 Version & Regression Information
Occurs in v4.2.3 and v4.3.0-beta. Behaviour appears consistent since nullish coalescing was first introduced in v3.7.
⏯ Playground Link
Playground link with relevant code
💻 Code
interface A {
b?: B;
}
interface B {
c: string;
}
(a: A): void => {
// Works, but intended behaviour is unclear
if (a.b?.c) a.b.c.length;
// Doesn't work 🙁
if (a.b?.c ?? "") a.b.c.length;
// ^ Object is possibly 'undefined'. ts(2532)
// Not very concise 🙁
if (a.b?.c !== undefined && a.b.c) a.b.c.length;
};
It's an edge case with a good use case. @typescript-eslint/strict-boolean-expressions
helps avoid tricky bugs by requiring code to separately handle nullish vs. falsy values. Nullish coalescing would be the simplest way to explicitly treat nullish values the same as an empty string.
This might be related to #38136 but I'm unsure.