Skip to content

Proposal: Support spread operator for tuples in function calls #17934

Closed
@jp-hoehmann

Description

With current versions of TypeScript, this is an error:

((_) => {})(...[null]); // ERROR: Expected 1 arguments, but got a minimum of 0.

In order to make this code work, the developer needs to tell the type checker to shut up, which could look like this:

(((_) => {}) as any)(...[null]); // Working fine.

This is unfortunate, as passing arguments for functions around in tuples is a common pattern in functional programming and there is currently no way to do it safely in TypeScript.

This was mentioned in #5296, which lead to the spread operator being supported for arrays. Supporting tuples in addition to arrays is not a straightforward change, since tuples can currently have additional values, which are not type checked (there is proposal #6229, which aims to fix this):

function f(s: string, a: number, b: number, c: number,  ...rest: number[]) {
    // ...
}
// legal
let quad: [string, number, number, number, number] = ["foo", 1,2,3,4];
f(...quad); // and triple

quad = ["foo", 1, 2, 3, 4, "boo!"]; // it is legal currently
f(...quad); // now it blows up in run time because rest has a string

Here is a longer and more detailed example taken from #5296 showing the desired behavior in detail:

function f(s: string, a: number, b: number, c: number,  ...rest: number[]) {
    // ...
}
function g(s: string, a: number, b: number) {
}
// legal
let quad: [string, number, number, number, number] = ["foo", 1,2,3,4];
let triple: [string, number, number, number] = ["foo", 1,2,3];
let double: [string, number, number] = ["foo", 1,2];
f(...quad); // and triple
f(...double, 3);
f("foo", ...[1,2,3]);
f(...quad, 1, ...[1,2,3]); // and triple
g(...double);
// illegal
f(...double); // too short -- double doesn't match parameter 'c'
g(...triple); // too many parameters
g(...quad); // too many parameters

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions