Skip to content

Type narrowing for two variables #25492

Answered by mdazfar2
NitishKumar525 asked this question in Q&A
Discussion options

You must be logged in to vote

@NitishKumar525 The Typescript compiler does not track dependencies between different variables in this way, so it doesn't "remember" that a.type and b.type are equal, for instance. This has been variously requested as a feature, but e.g. this issue shows the Typescript team don't currently consider it worth implementing.

If it was my code, I would probably write it this way:

 switch (a.type) {
    case "A": {
      return b.type === "A" && a.propsOfA === b.propsOfA;
    }
    case "B": {
      return b.type === "B" && a.propsOfB === b.propsOfB;
    }
    case "C": {
      return b.type === "C" && a.propsOfC === b.propsOfC;
    }
  }

That's three checks instead of nine. However, this migh…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@NitishKumar525
Comment options

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