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

会有一股神秘感。 提交于 2019-11-29 11:06:17

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)


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]) => {
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!