Skip to content

Improve Array.from(tuple) and [...tuple] #27859

@KSXGitHub

Description

@KSXGitHub

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions