thedayturns
thedayturns

Reputation: 10823

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:

Upvotes: 2

Views: 816

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159855

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;
  }
}

Upvotes: 4

Related Questions