Skip to content

Discriminating between two anonymous types #13459

Closed
@johnfn

Description

@johnfn

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. It's also not DRY.
  • Give them both a common type property. Again, seems like overkill for types that are only used as arguments for one function.
  • Unify both types into { foo: number, bar?: never } | { bar: string, foo?: never }. This feels like a hack that will confuse other developers when they look at my type signatures.

What I would like would be to do this:

if (x.foo) { /* x has been inferred to be { foo: number } */

Is there a reason that is not possible?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions