I want to know if there is a simple way of overloading function property of an object in typescript. Example:
interface Doable {
do(s: number): number;
do(s: string): string;
}
let obj: Doable = {
do(s: number): number;
do(s: string): string;
do(s: number | string) {
return s;
}
}
The compiler here will raise an error complaining that do
property is duplicate. Is there another way of declaring the function without using any
?
I already know that this implementation will work.
let obj: Doable = {
do(s: any) {
return s;
}
}
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.
Unlike the other programming languages, JavaScript Does not support Function Overloading.
And C doesn't support Function Overloading.
If you need to do this without relying on an interface, you can accomplish this by overloading a function in the scope of the object literal and then setting it on the literal.
example:
function myFunc(a : number) : number;
function myFunc(b : string, c : string) : boolean;
function myFunc(a : number | string, c? : string) : any{
//function impl goes here
}
const myLiteral = {
myFunc
};
This way you don't have to use any, and you can use functions with differing numbers of parameters. (The function definition returning any in my example is not used as one of the valid function signatures; only the first two definitions before the impl are.)
Got the idea from: https://www.typescriptlang.org/docs/handbook/functions.html (scroll to the bottom)
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