2

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

2

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!, the first solution worked as expected, and there was no need to try second one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.