Skip to content

Support concat operations on arrays of different types #26378

@limbo

Description

@limbo

Search Terms

concat, array, type

Suggestion

Currently concat requires that arrays be of similar types (or arrays of arrays of similar type). This requirement can be too strict at times. Since concat doesn't change the source arrays, it seems reasonable to return an array of the union of the input array types.

This can be achieved by adding an overload to Array.concat:

Array<T> {
  concat<U>(...items: (U | ConcatArray<U>)[]): Array<T|U>;
}

Use Cases

Joining dissimilar arrays.

Examples

Simple example below. A more realistic example would probably involve arrays of more complex, type-inferred objects that are mostly similar but slightly different.

const nums=[1,2,3];
const strs = ['a','b','c'];

// Currently, must do something like:
const arr1 = (nums as Array<string|number>).concat(strs);

// With this proposal we can instead use:
const arr2 = nums.concat(strs);

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