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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With