microsoft / microsoft/TypeScript

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

Open
#61,424 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow Help Wanted
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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

```ts
type Arr = Array | [] | [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:
```ts
type Arr = Array | [] | [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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and compare the inferred type for tuple destructuring with the indexed-access result. Review the related issue #55661 for context. Done means the destructured value is reported as potentially undefined in this mixed array-and-tuple union case without changing the correct indexed-access behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.