Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

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

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 trying

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

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

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

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.

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


What I've tried so far

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 => ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...