如何在TypeScript中重载方法?

时间:2017-09-11 06:27:25

标签: function oop typescript overloading

我有一个方法,它在签名中获取对象的参数。我想传递对象而不是许多参数,另一方面,我不想更改现有方法的签名,因为它已经在多个地方使用了。所以基本上我想要两种方法。但是当我尝试编写代码时,它会给我错误Duplicate function implementation

    getSearchData(fetchData: FetchData,languageCode: string, sorting: string, maxResultCount: number, skipCount: number): Observable<PagedResultDtoOfFetchData> {

    getSearchData(dataLevel: number, codeType: number, dataCode: string, descLong: string, languageCode: string, dataParent: string, sorting: string, maxResultCount: number, skipCount: number): Observable<PagedResultDtoOfFetchData> {

FYI dataLevel, codeType, dataCode, descLong, dataParentfetchData的属性。

1 个答案:

答案 0 :(得分:1)

Typescript能够重载函数,但与其他OOP语言(如C ++)相比,它具有一些特殊性。查看ref并且尽管您的方法具有不同数量的参数,但我可以通过这样做来避免编译器错误:

class FunOverloadClass {
    getSearchData(dataLevel: number, codeType: number, dataCode: string, descLong: string, languageCode: string, dataParent: string, sorting: string, maxResultCount: number, skipCount: number): Observable<PagedResultDtoOfFetchData>;
    getSearchData(fetchData: FetchData, languageCode: string, sorting: string, maxResultCount: number, skipCount: number): Observable<PagedResultDtoOfFetchData>;

    getSearchData(stringOrNumberParameter: any, secondParam: any, thirdParam: any, fourthParam: any, fifthParam: any, dataParent?: string, sorting?: string, maxResultCount?: number, skipCount?: number): string {
        if (stringOrNumberParameter && typeof stringOrNumberParameter == "number")
            alert("Variant #1: numberParameter = " + stringOrNumberParameter);
        else
            alert("Variant #1: stringParameter = " + stringOrNumberParameter);
    }
}

我使用dataParent?: string,其中?:运算符指定dataParent类型的string参数是可选