Ignore the fact that this is bad add
function. It\'s a question about using array destructuring with spread syntax in TypeScript.
This is what I\'m tryi
My bad, the answer is as simple as:
const add = ([x, ...xs]: number[]) => {
if (x === undefined)
return 0
else
return x + add(xs)
}
console.log(add([1, 2, 3])); //=> 6
add(["", 4]); // error
(code in playground)
You can do this:
const add: (nums: number[]) => number = ([x, ...xs]) => {
if (x === undefined)
return 0
else
return x + add(xs)
}
You can also use a type alias:
type AddFunction = (nums: number[]) => number;
const add: AddFunction = ([x, ...xs]) => {
...
}