Skip to content

Exhaustive type checking not working when class field to match on is a union #40160

Closed

Description

@francium

TypeScript Version: Nightly (v4.1.0-dev.20200807)

Search Terms: Tagged union, discriminated union, exhaustive checking

Code
TypeScript Playground Example

class Either<T> {
  public static Left<T>(value: T): Either<T> {
    return new Either('left', value);
  }

  public static Right<T>(value: T): Either<T> {
    return new Either('right', value);
  }

  private constructor(
    public readonly kind: 'left' | 'right',
    public readonly value: T
  ) {}
}

function doSomething(): string {
  const e = Either.Left('foo');

  // e.kind: 'left' | 'right';
  switch (e.kind) {
    case 'left':
      return e.value;
    case 'right':
      return e.value;
    // case 'foo':      as expected, this doesn't work
    //   break;
    default:
      const _exhaustiveCheck: never = e;        // even though we've matched against all the possible cases of `kind`, compiler still complains here
      throw new Error("How did we get here?");
  }

}

However this can be made to work if we did this,

interface Left {
  kind: 'left';
  value: string;
}
interface Right {
  kind: 'right';
  value: string;
}
type Either = Left | Right;

Playground
Now doing switch (e.kind) would perform the right checks.

Expected behavior:
Exhaustive type checking should work in the case with the class Either and kind: 'left' | 'right'.

Actual behavior:
Exhaustive type checking fails even though compiler understand the union only has 2 fields (e.g. case 'foo' is an error).

Activity

  1. jack-williams commented on Aug 21, 2020

    @jack-williams
    Collaborator

    Duplicate of #38963. The narrowing of a property is not propagated back to the parent object unless the parent is a discriminated union type.

    You can use the property as evidence of unreachability:

    const _exhaustiveCheck: never = e.kind;
    throw new Error("How did we get here?");

    In theory being able to conjure any value of type never is sufficient to show that the statement is unreachable.

  2. typescript-bot commented on Aug 23, 2020

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions