Co-dependency of variables destructured from union types is lost unless used in control-flow statements
#55,344 opened on 2023幎8æ12æ¥
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð Search Terms
destructuring union type tuple
Please expand this list or edit the title with a better-fitting description.
ð Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about n/a
⯠Playground Link
ð» Code
declare const val1: readonly ['a', 'a'] | readonly ['b', 'b'];
// ^?
const [v1, v2] = val1;
const val2 = [v1, v2] as const;
// ^?
// Is no longer readonly ["a", "a"] | readonly ["b", "b"]
ð Actual behavior
When destructuring a variable readonly ["a", "a"] | readonly ["b", "b"] into [v1, v2] = val, the compiler is sophisticated enough to retain the dependency of the two when either is used in either an if or even a switch statement:
if(v1 === 'a') {
v2;
// ^?
// TS is smart enough to know that this is "a"
}
When put back together, however, that dependency is lost. For:
declare const val1: readonly ['a', 'a'] | readonly ['b', 'b'];
const [v1, v2] = val1;
const val2 = [v1, v2] as const;
val1 and val2 should be identical, however, val2 is readonly ["a" | "b", "a" | "b"]. Note that this not only applies to tuples, but de- and restructured objects as well.
See this real example of a legitimate use-case and how this affects the code.
ð Expected behavior
Just like with
if(v1 === 'a') {
v2;
// ^?
// TS is smart enough to know that this is "a"
}
the compiler should figure out that v1 and v2 depend on each other when combining them with e.g. [v1, v2] and create an according union type of tuples instead of a single tuple with union type members.