Skip to content

Unable to append a type to an existing tuple #31286

Description

@Roaders

TypeScript Version: 3.2.4

Search Terms:
Tuple, merge, combine

Code

function combine<T, U extends any[]>(item: T, items: U): [T, ...U] {
    return [] as any;
}
const result = combine("hello", ["goodbye", 123, true]);

Expected behavior:
result should be typed as [string, string, number, boolean].

Actual behavior:
Compile error:
A rest element type must be an array type.

Playground Link:
Link

Related Issues:

Activity

  1. lll000111 commented on May 7, 2019

    @lll000111

    Your playground link links to an empty Playground.

    Correct link with code.

  2. Roaders commented on May 7, 2019

    @Roaders
    Author

    sorry about that, link in original post fixed.

  3. jcalz commented on May 7, 2019

    @jcalz
    Contributor

    Duplicates #5453 and fixed in TS3.0 by #24897 via tuples in rest/spread positions:

    type Cons<H, T extends any[]> = ((h: H, ...t: T) => void) extends ((
      ...r: infer R
    ) => void)
      ? R
      : never;
    
    function combine<T, U extends any[] | [any]>(item: T, items: U): Cons<T, U> {
      const ret = items.slice() as Cons<T, U>;
      ret.unshift(item);
      return ret;
    }
    const result = combine("hello", ["goodbye", 123, true]);
    // const result: [string, string, number, boolean]

    Note: this should be called "prepend", not "append". Appending to and concatenating tuples is an open issue (#26058) with workarounds of various levels of hackiness available.

  4. Roaders commented on May 7, 2019

    @Roaders
    Author

    That's an ...interesting way of fixing this!

    Updated link

    This is a hack though right? It's a very roundabout way of fixing the issue IMHO.

    Very appreciative of the solution though :-)

  5. jcalz commented on May 7, 2019

    @jcalz
    Contributor

    It's a hack in that it's roundabout, but that's probably a separate issue #26113. But this definition of Cons uses all supported and documented language features, so it's not a hack in the sense that "it just happens to work".

  6. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions