I'm using Typescript 2.3.3
I'm trying to create a nice API for some code I'm writing, so I'm experimenting with what's possible in Typescript's generics.
I'd like to be able to call a function with a generic type, and use that type to present choices to the user, some of which may be functions with different signatures.
Here's my attempt so far.
I declared an interface with two bare function signatures (the two options I'd 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, though, where to assign those implementations or how to create a return object that meets api's specification.
Is this even possible?
It's possible. You could 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 createApi function just returns an inner, overloaded function.
For more information on TypeScript overloads, see the Overloads section in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With