Here is a clever solution to the problem at hand.
Check out this example below:
interface HandleNumbers {
add(arg: number): number
}
interface HandleStrings {
concat(a: string, b: string): string;
}
class Api {
add = (arg: number) => arg + 1
concat = (a: string, b: string) => a.concat(b)
}
interface HandleHttp {
<T extends void>(): {};
<T extends string>(): HandleStrings;
<T extends number>(): HandleNumbers;
}
const handleHttp: HandleHttp = <_ extends string | number>() => new Api();
handleHttp<number>() // you can only call [add] method
handleHttp<string>() // you can only call [concat] method
handleHttp() // unable to call any method
Remember that your resulting JS code will include both the add
and concat
methods.
Therefore, your ability to invoke these methods is influenced by the provided generic type.
For further information, visit here