Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spreading array to arguments in typescript

Tags:

typescript

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.

like image 772
OliverRadini Avatar asked Apr 18 '19 08:04

OliverRadini


1 Answers

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);
like image 183
Daniel Avatar answered Sep 30 '22 05:09

Daniel