如何在TypeScript中使用不同的返回类型编写重载方法?

时间:2018-06-08 13:36:46

标签: javascript typescript methods signature

我想创建一个方法,如" attr"您可以通过传入所需属性的名称或要设置的名称和值来使用它来获取或设置html元素的属性。在jQuery中它看起来像这样:

$('#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.  

我还希望typescript根据它的使用方式显示正确的返回类型。

1 个答案:

答案 0 :(得分:0)

这称为方法重载,在打字稿中,它通过提供方法签名列表来完成。

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;
}