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

前端 未结 1 1391
死守一世寂寞
死守一世寂寞 2020-12-19 10:30

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

相关标签:
1条回答
  • 2020-12-19 11:10

    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]) => {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题