我想编写一个名为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?
最简单的方法是过载:
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}`)
})
}
您可以使用重载:
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}`)
})
}