thedayturns thedayturns - 2 months ago 7
TypeScript Question

How do I discriminate between two different object types in TypeScript?

Say I have the following code:

function myFunction(x: { foo: number } | { bar: string }) {


How can I write some code to determine whether
x
is the first or second type?

Things I've considered:


  • Writing an
    x is MyType
    function to check for a
    foo
    property. Yes, I could do this, but it seems overkill for types that are only used as arguments to a single function.

  • if ((x as { foo: number}).foo) { let y = x as { foo: number }
    . I could do this, but it defeats the point of a type system.

  • Give them both a common
    type
    property. Again, seems like overkill for types that are only used as arguments for one function.


Answer

It is also a work-around, but you can unify the fields of the types by extending your existing types with optional fields typed to never so that each type theoretically has every field possible in the union:

{ foo: number, bar?: never } | { bar: string, foo?: never }

By making the superset type contain all the fields you can run type checks like:

type CompletelyDisjointed = { foo: number, bar?:never } | { foo?: never, bar: string };

function myFunction(x: CompletelyDisjointed): string | number {
    if (typeof x.bar === 'string') {
        return x.bar;
    } else {
        return x.foo;
  }
}
Comments