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:
Suggestion
Array.from(tuple)and[...tuple]should preserve individual types that made up tuple.Proposal
Array.from(Simple)Add this overload to
Array.from:demo 1
Caveats:
Array.prototypewhilst actualArray.fromdiscards them. (for instance, if input hasfoo: 'bar', output array will also hasfoo: 'bar').Array.from(Complete)Fix above caveats.
demo 2
Spread operator
Note that
typeof clonedoes not contain{ foo: 'bar' }.Use Cases
Examples
Clone a tuple
Clone a generic tuple
Checklist
My suggestion meets these guidelines: