-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Description
TypeScript Version: 3.5.1
Search Terms:
destructure tuple destructuring
Code
function tuple(): [null, string] | [string, null] {
if (Math.random() < 0.5) {
return [null, 'a string'];
}
return ['a string', null];
}
const arr = tuple();
if (arr[0] === null) {
arr[1].toUpperCase(); // <-- 👍 Works! TS knows arr[1] is a string
}
const [a, b] = tuple();
if (a === null) {
b.toUpperCase(); // <-- 🚨 Error! TS doesn't know b is a string
}
Expected behavior:
TS can refine the destructured variables based on the function union return type.
Actual behavior:
Error.
It makes sense that when I do
const [a, b] = tuple();
That at that point, a
and b
need to both have an inferred type of null | string
.
But when inside the conditional check if (a === null)
I was expecting type refinement. Maybe that's an impossibility, but TS has gotten so smart I was genuinely surprised it wasn't able to refer that b
was a string
at that point.
Related Issues:
maybe #28311 ?
Metadata
Metadata
Assignees
Labels
No labels