3

An example setup:

type A = {
  type: 'A';
  foo: string;
  baz: number;
}

type B = {
  type: 'B';
  bar: string;
  baz: number;
}

type Unioned = A | B

This works fine:

function handle(x:Unioned) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}

However, I get an error with this:

function handle(x:Omit<Unioned, 'baz'>) {
  if (x.type === 'A') {
    console.log(x.foo)
  }
}

Specifically, the error I get is: Property 'foo' does not exist on type 'Omit<Unioned, "baz">'.

I would expect that typescript can infer the type of x within the if statement is actually Omit<A, 'baz'>, but it doesn't.

What is it about using Omit that causes this to happen? And how can I make this work as expected?

rbhalla
  • 869
  • 8
  • 32
  • 2
    The problem is that `Omit` does not *distribute* across unions in `T`. You need to use a distributive version of `Omit` if you want to use it with unions, as shown [here](https://tsplay.dev/mAd2QN). Please see the answers to the questions linked above for more information. – jcalz Dec 20 '22 at 03:05

0 Answers0