Typescript: how to distinguish between multiple types by a deeply nested value?

Viewed 35

I'm trying to make typescript select the appropriate type from deeply nested value. (It works for values nested one level deep).

    type A = {
        foo: {
          bar: 'asdf1';
        };
        bar: 'asdf1';
      };

      type B = {
        foo: {
          bar: 'asdf2';
        };
        bar: 'asdf2';
      };

      const x: A | B = { foo: { bar: 'asdf1' }, bar: 'asdf1' } as A | B;

      switch (x.foo.bar) {
        case 'asdf1':
          console.log(x.bar);
          break;
        default:
          break;
      }

But typescript is not able to guess that there will be 'asdf1' printed out. enter image description here

How can I make Typescript deduct the type of x.bar from x.foo.bar?

Thanks for any ideas.

0 Answers
Related