thedayturns thedayturns - 1 year ago 59
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
is the first or second type?

Things I've considered:

  • Writing an
    x is MyType
    function to check for a
    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
    property. Again, seems like overkill for types that are only used as arguments for one function.

Answer Source

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 === 'string') {
    } else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download