Reputation: 4413
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
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