Skip to content
Discussion options

You must be logged in to vote

You'll need to narrow down the type of Foo | undefined which is ultimately A | B | undefined.

To achieve this, you can use the in operator to narrow down the type.

type A = {
    episode: string;
    id: number;
}

type B = {
  id: number;
}

type Foo = A | B;

function test(value: Foo | undefined) {
  if (!value) {
    return value;
    //     ^? (parameter) value: undefined
  }

  if ('episode' in value) {
    return value;
    //     ^? (parameter) value: A
  }

  return value;
  //     ^? (parameter) value: B
}

🔗 TypeScript Playground.

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@acjo85
Comment options

@charpeni
Comment options

Answer selected by acjo85
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants