In Typescript, how can I implement a function interface with overloads?
I am using Typescript 2.3.3
I am trying to create a nice API for some code I write, so I am experimenting with what is possible in generics Typescript.
I would like to be able to call a function with a generic type and use that type to present a selection to the user, some of which might be functions with different signatures.
Here's my attempt.
I have declared an interface with two bare function signals (two options that I would like to present to the developer):
interface api<T1> {
<T2>(second: T2): {
first: T1
second: T2;
};
<T2, T3>(second: T2, third: T3): {
first: T1
second: T2;
third: T3;
};
}
And I create a function that contains the implementations of each function signature using the generic type parameter passed to it:
const test = <TFirst>(first: TFirst) : api<TFirst> => {
const impl1 = <T2>(second: T2) => ({
first, second
});
const impl2 = <T2, T3>(second: T2, third: T3) =>({
first, second, third
});
return ...?
};
I have no idea where to assign these implementations or how to create a returned object that conforms to the api spec.
Is it possible?
source to share
It is possible. You can do something like this:
interface api<T1> { <T2>(second: T2): { first: T1; second: T2; }; <T2, T3>(second: T2, third: T3): { first: T1; second: T2; third: T3; }; }; function createApi<T1>(first: T1): api<T1> { function impl<T2>(second: T2): { first: T1; second: T2; }; function impl<T2, T3>(second: T2, third: T3): { first: T1; second: T2; third: T3; }; function impl<T2, T3>(second: T2, third?: T3): { first: T1; second: T2; third?: T3; } { if (third === undefined) { return { first, second }; } return { first, second, third }; } return impl; } const test = createApi<number>(1); console.log(test(2)); console.log(test(2, 3));
The function createApi
only returns an internal, overloaded function.
For more information on TypeScript overloads, see the Overloads section in the documentation .
source to share