Microsoft/TypeScript

Co-dependency of variables destructured from union types is lost unless used in control-flow statements

Open

#55.344 aberto em 12 de ago. de 2023

Ver no GitHub
 (2 comments) (2 reactions) (0 assignees)TypeScript (6.726 forks)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

🔎 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

https://www.typescriptlang.org/play?ts=5.1.6#code/CYUwxgNghgTiAEYD2A7AzgF3gNyhAjAFzxxTCoQCe8A2gORR0A08DdAuvAD4khkXV6AI2asR7ANwAoAPQz4CxUoUA9APxSpydFhrZ8LbACZOAXhx580rakwWIR+Ob0GcJ+FDSJbGaXKXqsvIAkl4oSPAQqADmIDC8-ChUtABEUCksaSmcPKTkSYIpQhnwRdlSQA

💻 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.

Guia do colaborador