wenkang lin
wenkang lin

Reputation: 129

How to declare overloads function with same parameters, different return type in TypeScript?

I have a function that can be curried(functional programming), I declare it as below:

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number, list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number) => (list: T[]) => T[];

But in this case, the last line of code will never work because it has same parameters with the penultimate line.

I also consider the Union Types, just like:

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): ((index: number, list: T[]) => T[]) | ((index: number) => (list: T[]) => T[]);

But it will cause a ts mistake:

TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((index: number, list: number[]) => number[]) | ((index: number) => (list: number[]) => number[])' has no compatible call signatures

So, How can I correct it?

Upvotes: 1

Views: 50

Answers (1)

christoph rodak
christoph rodak

Reputation: 86

You can use a interface with call signature as your return type for the last function:

declare interface AdjustReturnFunction<T>{
    (index: number, list: T[]): T[];
    (index: number): (list: T[]) => T[];

}

declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): AdjustReturnFunction<T>;

Upvotes: 1

Related Questions