What would be the easiest way to achieve / implement such a function overload in TypeScript?
function Foo(
param1: number,
param2: string,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void { .... }
function Foo(
param6: number,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void { .... }
It's covered in Overloads section of the Functions docs, but in your case it can be like this:
function Foo(
param1: number,
param2: string,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void;
function Foo(
param6: number,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void;
function Foo(...args: any[]): void {
if (args.length === 5) {
// 1st signature
} else if (args.length === 4) {
// 2nd signature
} else {
// error: unknown signature
}
}
(code in playground)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With