George
George

Reputation: 4413

How do I write overloaded method with different return types in TypeScript?

I want to create a method such as "attr" where you can use it to get or set an attribute of an html element by passing in just the name of the attribute you want or the name and the value you want to set. In jQuery it would look like this:

$('#awesome-element').attr('cool-attr'); // this will return the current value of cool-attr.
$('#awesome-element').attr('cool-attr', 'cool-value'); //this will set the value of cool-attr and return a jquery object for chaining.  

I also want typescript to show the correct return type depending on how it is being used.

Upvotes: 2

Views: 775

Answers (1)

George
George

Reputation: 4413

This is called method overloading and in typescript it is done by providing a list of method signatures.

public attr(name: string):string;
public attr(name: string, value:{}):jQuery;
public attr(name: string, value?:{}):string|jQuery{
    //if we dont have a value we need to return a string as it means we are getting the attribute
    if(value === undefined){
        /*logic for getting the attribute goes here*/
        return "";
    }
    //else we are setting a value so we will return this for chaining
    /*logic for setting the attribute goes here*/
    return this;
}

Upvotes: 1

Related Questions