In TypeScript it is possible to declare a function with "Rest Parameters":
function test1(p1: string, ...p2: string[]) {
// Do something
}
Suppose that I declared another function that called test1
:
function test2(p1: string, ...p2: string[]) {
test1(p1, p2); // Does not compile
}
The compiler produces this message:
Supplied parameters do not match any signature of call target: Could not apply type 'string' to argument 2 which is of type 'string[]'.
How can test2
call test1
will the supplied arguments?
In the function chapter, you learned about functions and their parameters. TypeScript introduced rest parameters to accommodate n number of parameters easily. When the number of parameters that a function will receive is not known or can vary, we can use rest parameters.
A rest parameter allows us to pass zero or any number of arguments of the specified type to a function. In the function definition where we specify function parameters rest parameters should always come at last or the typescript compiler will raise errors.
Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. But the spread syntax expands iterables into individual elements.
Try the Spread Operator. It should allow for the same effect as in Jeffery's answer but has a more concise syntax.
function test2(p1: string, ...p2: string[]) {
test1(...arguments);
}
There's no way to pass p1 and p2 to test1 from test2. But you could do this:
function test2(p1: string, ...p2: string[]): void {
test1.apply(this, arguments);
}
That's making using of Function.prototype.apply and the arguments object.
If you don't like the arguments object or you don't want all the arguments passed in exactly the same order you can do something like this:
function test2(p1: string, ...p2: string[]) {
test1.apply(this, [p1].concat(p2));
}
Yes, it doesn't compile as you are doing wrong thing. Here is the right way:
function test1(p1: string, ...p2: string[]) {
// Do something
}
function test2(p1: string, ...p2: string[]) {
test1(p1, ...p2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With