If you want to define two overloads and specify the logic in a single function, you can do so with the following code snippet.
function myfunc(...values : Array<number>): number;
function myfunc(values : Array<number>): number;
function myfunc(value : (Array<number> | number), ...values : Array<number>): number {
if (typeof value === 'number') {
values.unshift(value);
} else if (value === undefined) {
values = [];
} else {
values = value;
}
// logic
return values.length;
}
myfunc(); // valid
myfunc(1); // valid
myfunc(1, 2); // valid
myfunc([1, 2]); // valid
myfunc(1, 2, 3, 4); // valid
myfunc([1, 2, 3]); // valid
// myfunc([1, 2, 3, 4], 5, 6); // error
// myfunc([1, 2], [3, 4]); // error
console.log(myfunc(1, 2, 3)) // outputs 3
console.log(myfunc([1, 2, 3])) // outputs 3
In this example, not defining an interface for an array followed by values leads to an error, which is the expected behavior. You can view an example here. It's important to check for undefined as transpiled JavaScript does not account for different function overloads, resulting in a single implementation where value
can be undefined.