如何使用扩展语法将TypeScript类型添加到结构化参数中? [英] How to add TypeScript types to destructured parameters using spread syntax?

查看:75
本文介绍了如何使用扩展语法将TypeScript类型添加到结构化参数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

忽略这是错误的add函数的事实.这是关于在TypeScript中使用数组分解和扩展语法的问题.

Ignore the fact that this is bad add function. It's a question about using array destructuring with spread syntax in TypeScript.

这就是我正在尝试的

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

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

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

But I have no idea how to add TypeScript types to this. My best guess is to do something like this (most direct translation)

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)之类的丑陋东西交织在一起-即使我将这些抽象为它们自己的函数,这不是重点.

Both functions work, but in TypeScript I lose the ability to destructure the array parameter and the function body is junked up with a bunch of ugly stuff like xs[0] and xs.slice(1) – even if I abstract these into their own functions, that's besides the point.

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

Is it possible in add types to destructured spread parameters in TypeScript?

到目前为止我尝试过的事情

类似的事情适用于固定数组

Something like this works for fixed arrays

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

但是我当然需要可变长度的数组输入.我试过了,但是没有编译

But of course I need variable length array input. I tried this, but it doesn't compile

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

推荐答案

我的错,答案很简单:

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)
}

您还可以使用类型别名:

You can also use a type alias:

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

const add: AddFunction = ([x, ...xs]) => {
    ...
}

这篇关于如何使用扩展语法将TypeScript类型添加到结构化参数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆