Microsoft/TypeScript

Potentially-`undefined` value not flagged when destructuring union of empty tuple and array

Open

#61,424 建立於 2025年3月14日

在 GitHub 查看
 (4 留言) (1 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: check: Control FlowHelp Wanted

倉庫指標

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

描述

🔎 Search Terms

"tuple destructuring", "tuple narrowing"

🕗 Version & Regression Information

This bug appears to occur as far back as TS 3.3 up to the current nightly build, as tested in the Playground.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.2#code/C4TwDgpgBAggTnKBeWCCGIA8A7ArgWwCMI4A+KAHygG0BdSmgZ2DgEtsBzWgbgCheAJhADGAGzRxowgPbZmUCXABcqOH14y5wGmnopFfNADpg0gMot2HABQBKblAD0jqAFEAHpGHAIAlSThpOCNYb1w0URVsaSgAoJDAGXJ+TXlCZAUEagAGHl5CE3NLTjsHZzdPER8-WIR40OBwyJrA4KhAUHJ+XigoIA

💻 Code

type Arr = Array<number> | [] | [string];

declare const arr: Arr;

const [a] = arr;
a.toString(); // Expected: error. Actual: no error. ❌

const b = arr[0];
b.toString(); // Expected: error. Actual: error. ✅

.d.ts from Playground:

type Arr = Array<number> | [] | [string];
declare const arr: Arr;
declare const a: string | number | undefined;
declare const b: string | number | undefined;

🙁 Actual behavior

When destructuring a value whose type is an array, an empty tuple, and a non-empty tuple, the destructured value isn't flagged as possibly undefined which caused a runtime error. The value is correctly flagged as possibly undefined when accessing it by index.

🙂 Expected behavior

When destructuring a value whose type is an array, an empty tuple, and a non-empty tuple, the destructured value should be flagged as potentially being undefined.

Additional information about the issue

This seems related to #55661 except, in this case, the union contains a mix of tuples and an array.

貢獻者指南