Microsoft/TypeScript

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

Open

#55,344 建立於 2023年8月12日

在 GitHub 查看
 (2 留言) (2 反應) (0 負責人)TypeScript (6,726 fork)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

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

貢獻者指南