注释允许数组或params传播作为参数的TypeScript函数?

问题描述 投票:0回答:2

我想编写一个名为printNums()的函数,它允许两者:

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

在普通JS中,该函数看起来像:

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

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

在TypeScript中,我如何编写/注释nums param?

typescript annotations
2个回答
2
投票

最简单的方法是过载:

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}`)
  })
}

1
投票

您可以使用重载:

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}`)
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.