最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Type args in typescript - Stack Overflow

programmeradmin4浏览0评论

I have this situation in my typescript code:

const first = (value: any[]) => {

}
const test = (...args: any[]) => first(...args);

In function test I pass all params in first function. first(...args).

Doing this I get a typescript error: A spread argument must either have a tuple type or be passed to a rest parameter.(2556).

I notice many answers on this topic but they don't solve my issue.

How to solve this issue?

I have this situation in my typescript code:

const first = (value: any[]) => {

}
const test = (...args: any[]) => first(...args);

In function test I pass all params in first function. first(...args).

Doing this I get a typescript error: A spread argument must either have a tuple type or be passed to a rest parameter.(2556).

I notice many answers on this topic but they don't solve my issue.

How to solve this issue?

Share Improve this question edited Sep 8, 2021 at 14:42 Donald Duck is with Ukraine 8,91223 gold badges79 silver badges102 bronze badges asked Sep 8, 2021 at 6:52 AskingAsking 4,24021 gold badges82 silver badges163 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

The error means that you need to use an Array and spread arg within it:

const first = (value: any[]) => {};
const test = (...args: any[]) => first([...args]);

Playground Link

Your first() function expects to get an array/tuple.
So you can simply pass the array.

const first = (value: any[]) => {};
const test = (...args: any[]) => first(args);

Playground

or you can make the first method accept variable arguments:

const first = (...value: any[]) => {};
const test = (...args: any[]) => first(...args);

Playground

Typescript can be used to capture variable number of arguments into an array in a way similar to other C-like languages:

function varArgs(...args: any[]) {
  console.log(args.length);
}

To pass the array to a function accepting a variable number of arguments, spread syntax can be used:

function varArgs(...args: any[]) {
  console.log(...args);
}

This approach works just as well with arrow functions:

let varArgs = (...args: any[]) => {
  console.log(...args);
}

Call first with args

const test = (...args: any[]) => first(args);
发布评论

评论列表(0)

  1. 暂无评论