Skip to content

Conditional type narrowing ignores nullish coalescing to falsy value #43705

Closed as not planned
@aaronadamsCA

Description

@aaronadamsCA

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions