-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Open
Labels
Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptThe issue relates to the different libraries shipped with TypeScriptIn DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript
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)
aleclarson, jcalz, brianle1301 and hurryabit
Metadata
Metadata
Assignees
Labels
Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptThe issue relates to the different libraries shipped with TypeScriptIn DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript