To learn more about the use of type parameters in a call signature, refer to the documentation here.
In this scenario, the interface defines an overloaded function that must adhere to both signatures. This can be achieved as demonstrated below:
function f<R>(paths: string[]): Observable<R>; // not feasible
function f<R>(func: (state: number) => R): Observable<R>;
function f<R>(something: string[] | ((state: number) => R)): Observable<R> {
if (Array.isArray(something)) {
return { someField: null as any as R }; // as you can see, it's not possible!
}
return { someField: something(2) };
}
const someInterfaceNumber: SomeInterface<number> = f;
The compilation of this code proceeds without errors. I hope this explanation clarifies things!
*Although in theory, you cannot achieve this, as stated in the first signature of a generic function that takes a string[]
parameter and returns an Observable<R>
for any caller-defined R
, which is practically unattainable since there is no tangible object of type R</code to return. Therefore, a workaround is to simulate it using <code>null as any as R
, but caution is advised when relying on such an interface.