4

Given the following:


type TestUnion = { a: true } | { b: true };
const shouldFail: TestUnion = { a: true, b: true };

I'd expect that shouldFail would have a compilation error since it doesn't match either side of the union. However, this is compiling just fine. (Typescript 3.5.1)

Am I misunderstanding something about how union types work?

  • 7
    It matches both sides of the union, but you are likely expecting excess property checking to happen. If so, [that's a known bug](https://github.com/microsoft/TypeScript/issues/20863). For now you should manually craft your union so as to be more prohibitive, if you care: `type TestUnion = {a: true, b?: never} | {a?:never, b: true}` – jcalz Jun 26 '19 at 16:04
  • Possible duplicate of [Typescript React: Union type for props does not display error when providing excess properties](https://stackoverflow.com/questions/52771362/typescript-react-union-type-for-props-does-not-display-error-when-providing-exc) – jcalz Jun 26 '19 at 16:08
  • 1
    [Union types are not intended to be automatically mutually exclusive](https://github.com/microsoft/TypeScript/issues/31055#issuecomment-485479365). See also https://stackoverflow.com/questions/42123407/does-typescript-support-mutually-exclusive-types?noredirect=1&lq=1 – artem Jun 26 '19 at 16:08
  • Possible duplicate of [Typescript React: Union type for props does not display error when providing excess properties](https://stackoverflow.com/questions/52771362/typescript-react-union-type-for-props-does-not-display-error-when-providing-exc) – Sean Vieira Jun 27 '19 at 02:52

0 Answers0