How to add TypeScript types to destructured parameters using spread syntax? How to add TypeScript types to destructured parameters using spread syntax? typescript typescript

How to add TypeScript types to destructured parameters using spread syntax?


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])); //=> 6add(["", 4]); // error

(code in playground)


Original answer:

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]) => {    ...}