2

I have a method which is taking object's parameters in the signature. I want to pass the object instead of to many parameters and on the other hand, I don't want to change the existing method's signature because it's being used already at multiple places. so basically I want both the methods. But when I'm trying to write code, it gives me errorDuplicate 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, dataParent are properties of fetchData.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197

1 Answers1

3

Typescript is able to overload functions, but it has some particularities in contrast with other OOP languages, such as C++. Looking ar the ref and despite the fact that your methods have a different number of arguments, I could avoid the compiler errros by doing this:

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

where I used dataParent?: string, where the ?: operator specifies that the parameter named dataParent of type string is optional.

gsamaras
  • 71,951
  • 46
  • 188
  • 305