microsoft / microsoft/TypeScript

Improve `Array.from(tuple)` and `[...tuple]`

Open
#27,859 7 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: lib.d.ts In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Suggestion

Array.from(tuple) and [...tuple] should preserve individual types that made up tuple.

Proposal

Array.from (Simple)

Add this overload to Array.from:

interface ArrayConstructor {
  from<T extends any[]> (array: T): T
}

demo 1

Caveats:

  • The above definition preserves everything including unrelated properties that do not belong to Array.prototype whilst actual Array.from discards them. (for instance, if input has foo: 'bar', output array will also has foo: 'bar').
Array.from (Complete)

Fix above caveats.

interface ArrayConstructor {
  from<T extends any[]> (array: T): CloneArray<T>
}

type CloneArray<T extends any[]> = {
  [i in number & keyof T]: T[i]
} & {
  length: T['length']
} & any[]

demo 2

Spread operator
declare const tuple: [0, 1, 2] & { foo: 'bar' }

// $ExpectType [string, string, 0, 1, 2, string, string]
const clone = ['a', 'b', ...tuple, 'c', 'd']

Note that typeof clone does not contain { foo: 'bar' }.

Use Cases

  • Clone a tuple without losing type information.

Examples

Clone a tuple
const a: [0, 1, 2] = [0, 1, 2]

// $ExpectType [0, 1, 2]
const b = Array.from(a)
Clone a generic tuple
function clone<T extends any[]> (a: T): T {
  return Array.from(a)
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

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

The issue names no repository files, tests, or entry points, so begin by reading the Array.from and spread proposals and their linked examples. Done means tuple element and length types remain preserved for the described Array.from and spread cases without changing JavaScript runtime behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.