microsoft / microsoft/TypeScript
Improve `Array.from(tuple)` and `[...tuple]`
Open
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
}
Caveats:
- The above definition preserves everything including unrelated properties that do not belong to
Array.prototypewhilst actualArray.fromdiscards them. (for instance, if input hasfoo: 'bar', output array will also hasfoo: '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[]
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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