Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload object function properties in typescript?

Tags:

typescript

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;
    }
}
like image 615
eAbi Avatar asked Jan 14 '16 20:01

eAbi


People also ask

Can you overload functions?

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.

Can you overload a function in JavaScript?

Unlike the other programming languages, JavaScript Does not support Function Overloading.

Can you overload C functions?

And C doesn't support Function Overloading.


1 Answers

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)

like image 86
Sterling Camden Avatar answered Sep 27 '22 20:09

Sterling Camden