A big shoutout to Gerrit0#7591 over at the TypeScript Community discord server for providing this valuable insight:
When it comes to TypeScript, narrowing down types across separate variables can be a bit tricky. For instance, if you have a variable like:
const x: [true, string] | [false, Error] = ...
and you check the first element of the tuple, TypeScript cleverly narrows down the type for you:
if (x[0]) {
// TypeScript recognizes x[1] as a string
}
However, things get a bit more complicated when you destructure the variable first, as TypeScript considers these two destructured variables to be unrelated:
const [isStr, val] = x
if (isStr) {
// val is now a string | Error, not just a string
}
Unfortunately, there isn't an easy workaround for this issue other than avoiding destructuring or making sure to narrow down the type before destructuring:
if (x[0]) {
const val = x[1] // val will be recognized as a string
}