-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Conditional type narrowing ignores nullish coalescing to falsy value #43705
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
Comments
why don't you use |
Why is |
It doesn't seem like this particular lint rule configuration is helping code clarity (for humans or machines). If this turns out to be a popular thing to write we can see about adding detection for it but generally we don't spend perf budget on handling constructs that don't change the code behavior. |
As an additional workaround, |
I can change the use case, sure, but I wanted to point out the gap anyway. Never know when a little thing points to a bigger thing. |
This is not testing only for Here is a simple code example that output an error in typescript, when it should not: const readProp = (property: string | undefined | null): string => {
if ((property ?? undefined) === undefined) {
return ''
}
return property;
// ~~~~~~~~
// Type 'string | null | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.
} Our Context: Anyway, there is a problem in the type checking / type guard when using nullish coalescing operator "??". |
FWIW, I long ago reconfigured our ESLint rules to use |
Bug Report
if (a.b?.c ?? false) a.b.c
does not narrow the type ofa.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
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.
The text was updated successfully, but these errors were encountered: