8

I have an array of arrays, and I'd like to use each as arguments for a function, for instance, in javascript it could look like:

const args = [
    [1, 'a'],
    [2, 'b'],
];

const concatter = (first, second) => `${first}-${second}`;

const test = args.map(a => concatter(...a));
console.dir(test);

I've tried something similar in typescript, but I'm having issues getting it to work. Here's a link to the playground. The code looks like this:

const args = [
    [1, 'a'],
    [2, 'b'],
];

const concatter = (first: number, second: string) => `${first}-${second}`;

const singleTest = concatter(...args[0]);
const test = args.map(a => concatter(...a));

However with this, the calls to concatter show the error:

Expected 2 arguments, but got 0 or more.

It seems as though I'm making a fairly basic error here, but I haven't yet been able to find any information on what that might be.

3
  • 2
    I'm curious why you'd use spread in this situation. Since you know concatter requires two arguments, why not just const test = args.map(([a,b]) => concatter(a, b));? Commented Apr 18, 2019 at 8:59
  • @T.J.Crowder Indeed I'd agree that that is a better solution, though I'm still interested in why spread doesn't work here Commented Apr 18, 2019 at 9:01
  • 1
    TypeScript doesn't appear to understand that the elements in args always have length 2, and as such will throw an error (since it assumes it could be of any length, even zero). Commented Apr 18, 2019 at 9:01

1 Answer 1

9

You just need to add a type for your args so TypeScript knows that the args variable is an array of tuples with a number and a string.

Then it will work:

const args: [number, string][] = [
    [1, 'a'],
    [2, 'b'],
];

const concatter = (first: number, second: string) => `${first}-${second}`;

const singleTest = concatter(...args[0]);

const test = args.map(a => concatter(...a));

console.log(test);
Sign up to request clarification or add additional context in comments.

5 Comments

TypeScript's static analysis is amazingly deep. :-)
Fantastic, this works in the playground; however, for the code I'm working on, this doesn't work; I get the error TS2556, I believe the same as was on the playground, Expected 2 arguments, but got 0 or more. I'm guessing this is to do with a typescript or tslint version?
@OliverRadini I think it might have been an issue in previous version of TypeScript. I tested with 3.4.2 and it works, but check out this issue on GitHub github.com/Microsoft/TypeScript/issues/4130
@Daniel For reference, upgrading my typescript from 2.4.1 to 3.4.3 got this to work
Thanks man. This docs also helped me achieving that. auth0.com/blog/typescript-3-exploring-tuples-the-unknown-type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.