Reputation: 814
Typescript/JavaScript question.
I created my own log()
method where I could switch logging on demand (not important), but right now I use a simple console.log()
. Here is the code:
log(message: any): void {
console.log(message)
}
Recently I decided to pass multiple parameters, since console.log
supports any number of parameters using like: console.log(a, b, c)
.
So, I decided to use rest parameter and adjust my method to the following:
log(...message: any[]): void {
console.log(message)
}
Works great. However, when I use my log
method with any number parameters, the console.log
outputs an array and not separate values as if I called it directly.
I can understand why, because the message could be seen as a single parameter of array type.
But how would I pass array to console.log
(or any other alike function) and tell that it is not a single parameter of array type, but multiple parameters?
I would really like to avoid defining 10 optional parameters passing them as is :)
Upvotes: 2
Views: 1683
Reputation: 641
There are at least 2 options for doing this:
Option 1:
log(...message: any[]): void {
console.log(...message)
}
Option 2: Use Function.prototype.apply
.
E.g.
log(...message: any[]): void {
console.log.apply(null, message)
}
This will apply your array of arguments as you expect.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Upvotes: 3