0

(Please feel free to edit the title if you can think of a better one.)

I have a discriminated union type below but even after doing a switch on the tag, I'm unable to get the type of another field. The code below has my questions in comments.

type AOrB = { type: 'A'; value: number } | { type: 'B'; value: string };

const fn = <T extends AOrB>(t: T) => {
  // t.type here is `'A' | 'B'`, which is correct.
  switch (t.type) {
    case 'A':
      // t.value here is `string | number` but should be `number`?
      break;
    case 'B':
      // t.value here is also `string | number` but should be `string`?
      break;
  }
};

Am I missing something or is this a bug in the compiler?

user1527166
  • 3,229
  • 5
  • 26
  • 26

1 Answers1

-1

I guess it happens because of the implied typing of 'type'. Both 'A' and 'B' are strings, so just by looking at {type: string, value: ...} the compiler cannot tell A from B. So you might need smth like TypeA and TypeB, to keep them apart: {type: TypeA, value: number} | {type: TypeB, value: number} and switch with typeof.

Maria K.
  • 219
  • 1
  • 8