Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to append a type to an existing tuple #31286

Closed
Roaders opened this issue May 7, 2019 · 5 comments
Closed

Unable to append a type to an existing tuple #31286

Roaders opened this issue May 7, 2019 · 5 comments

Comments

@Roaders
Copy link

Roaders commented May 7, 2019

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:

@lll000111
Copy link

lll000111 commented May 7, 2019

Your playground link links to an empty Playground.

Correct link with code.

@Roaders
Copy link
Author

Roaders commented May 7, 2019

sorry about that, link in original post fixed.

@jcalz
Copy link
Contributor

jcalz commented May 7, 2019

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.

@Roaders
Copy link
Author

Roaders commented May 7, 2019

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 :-)

@Roaders Roaders closed this as completed May 7, 2019
@jcalz
Copy link
Contributor

jcalz commented May 7, 2019

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants