7

忽略这是不好的add功能这一事实。这是一个关于在 TypeScript 中使用带有扩展语法的数组解构的问题。

这就是我正在尝试的

const add = ([x,...xs]) => {
  if (x === undefined)
    return 0
  else
    return x + add(xs)
}

console.log(add([1,2,3])) //=> 6

但我不知道如何向其中添加 TypeScript 类型。我最好的猜测是做这样的事情(最直接的翻译)

const add = (xs: number[]): number => {
  if (xs[0] === undefined)
    return 0;
  else
    return xs[0] + add(xs.slice(1));
};

console.log(add([1,2,3])); // => 6

这两个函数都可以工作,但是在 TypeScript 中,我失去了解构数组参数的能力,并且函数体被一堆丑陋的东西弄得像垃圾一样xs[0]-xs.slice(1)即使我将它们抽象成它们自己的函数,这也不是重点。

是否可以在 TypeScript 中向解构的展开参数添加类型?


到目前为止我尝试过的

这样的东西适用于固定数组

// compiles
const add = ([x,y,z]: [number, number, number]): number => ...

但当然我需要可变长度数组输入。我试过这个,但它没有编译

// does not compile
const add = ([x, ...xs]: [number, number[]]): number => ...
4

1 回答 1

5

我的错,答案很简单:

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

操场上的代码


原答案:

你可以这样做:

const add: (nums: number[]) => number = ([x, ...xs]) => {
    if (x === undefined)
        return 0
    else
        return x + add(xs)
}

您还可以使用类型别名:

type AddFunction = (nums: number[]) => number;

const add: AddFunction = ([x, ...xs]) => {
    ...
}
于 2017-02-19T00:44:34.027 回答