1

I want to write a function called printNums() that allows for both:

printNums(1, 2, 3)
printNums([1, 2, 3])

In plain JS, the function would look something like:

function printNums(nums) {
  if (!Array.isArray(nums)) {
    nums = [...arguments]
  }

  nums.forEach(num => {
    console.log(`Num: ${num}`)
  })
}

In TypeScript, how would I write/annotate the nums param?

2 Answers 2

3

Easiest way is an overload:

function printNums(...nums: number[]): void;
function printNums(nums: number[]): void;
function printNums(num1: number | number[], ...nums: number[]) {
  // safer than using [...arguments].
  const normalizedNums = Array.isArray(num1) ? num1 : [num1, ...nums];

  normalizedNums.forEach(num => {
      console.log(`Num: ${num}`)
  })
}
Sign up to request clarification or add additional context in comments.

3 Comments

What does ...nums do in the method parameter?
@MuratKaragöz It's known as Rest parameters in JavaScript: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Thanks for the answer, as well as helping with the type safety!
1

You can use overloads:

function printNums(...nums: number[]): void
function printNums(nums: number[]): void
function printNums(nums: number[] | number) {
    if (!Array.isArray(nums)) {
        nums = [...arguments] // not type safe but it will work
    }

    nums.forEach(num => {
        console.log(`Num: ${num}`)
    })
}

2 Comments

You answered first, but I'm going to accept the answer by Madara Uchiha because they gave a better type-safe alternative. Upvoted, thanks!
@saadq sure no problem. I did think about including a the rest of the parameters but decided against it as the ... will cause the data to first be copied to the extra param and then you copy it again to the final array (at least when targeting es5).. not ideal for a large abount of data but depends what you favor, type safety or perf

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.