Skip to content

Indirect narrowing of destructured discriminated union types works only for trivial cases. #48846

Closed
@DaviDevMod

Description

@DaviDevMod

Bug Report

Narrowing destructured discriminated union types using indirect control flow, works only for trivial cases in which the discriminant is a union of at most two types.

I found many issues related to discriminated unions, but they describe different problems.

🔎 Search Terms

discriminated

🕗 Version & Regression Information

Control Flow Analysis for Destructured Discriminated Unions has been introduced (or fixed) in TypeScript 4.6

The bug has been tested with the currently most recent version in the TypeScript Playground, which is v4.6.2

⏯ Playground Link

The discriminant is a union of at most two types: indirect narrowing works as expected.

The discriminant is a union of at least three types: indirect narrowing fails.

💻 Code

The discriminant is a union of at most two types and indirect narrowing works as expected:

type Food = 'TANGERINE' | 'PASTA';
type Cutlery = 'FORK' | 'SPOON';

type Meal = { food: 'TANGERINE'; cutlery?: never } | { food: 'PASTA'; cutlery: Cutlery };

function eat({ food, cutlery }: Meal) {
  if (food === 'TANGERINE') return cutlery;
  return cutlery;  // Correctly narrowed
}

The discriminant is a union of at least three types and indirect narrowing fails:

type Food = 'TANGERINE' | 'PASTA' | 'PIZZA';
type Cutlery = 'FORK' | 'SPOON';

type Meal = { food: 'TANGERINE' | 'PIZZA'; cutlery?: never } | { food: 'PASTA'; cutlery: Cutlery };

function eat({ food, cutlery }: Meal) {
  if (food === 'TANGERINE')  return cutlery;
  if (food === 'PIZZA')  return cutlery;
  return cutlery;  // Not narrowed
}

🙁 Actual behavior

Indirect narrowing doesn't work on destructured discriminated union when the discriminant is a union of at least three types.

🙂 Expected behavior

Destructured discriminated union should be narrowable indirectly, no matter how many types are involved in the discriminant.
If an implementation for a discriminant composed by an arbitrarily large number of types is not possible, I hope it is possible to at least raise the bar to five or even twenty types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions