Skip to content

Discriminated union limitation #10586

@alitaheri

Description

@alitaheri

Discriminated union types are limited to only one literal type property. This can be very useful sometimes when the same of objects are complex.

interface A1 {
  type: 'a';
  subtype: 1;
}

interface A2 {
  type: 'a';
  subtype: 2;
  foo: number;
}

interface B {
  type: 'b';
}

type AB = A1 | A2 | B;

const ab: AB = <AB>{};

if (ab.type === 'a') {
  // ab is A1 | A2, awesome! ♥
  if (ab.subtype === 2) {
    // ab is still A1 | A2 :( it should be A2

    ab.foo; // Error: foo doesn't exist on A1 | A2
  }
}

Expected behavior:
compile successful.

Actual behavior:
won't compile without explicit cast.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions