我有一个方法,它在签名中获取对象的参数。我想传递对象而不是许多参数,另一方面,我不想更改现有方法的签名,因为它已经在多个地方使用了。所以基本上我想要两种方法。但是当我尝试编写代码时,它会给我错误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, dataParent
是fetchData
的属性。
答案 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
参数是可选。