There exists a feature in typescript known as ReturnType<TFunction>
that enables one to deduce the return type of a specific function, like this
function arrayOf(item: string): string[] {
return [item]
}
Nevertheless, I am encountering difficulties when trying to utilize it with generic functions:
function arrayOf<T>(item: T): T[] {
return [item]
}
type R = ReturnType<typeof arrayOf> // R = {}[]
type R = ReturnType<typeof arrayOf<number>> // syntax error
// and so on.
Utilizing the primary answer from Typescript ReturnType of generic function, I have attempted the following: (note that this is not a duplicate, as the solution and question do pertain to this scenario)
function arrayOf<T>(x: T): T[] {
return [x];
}
type GenericReturnType<R, X> = X extends (...args: any[]) => R ? R : never;
type N = GenericReturnType<number, <T>(item: T) => T[]>; // N = never
I have also experimented with:
type GenericReturnType<TGenericParameter, TFunction> = TFunction extends (...args: any[]) => infer R ? R : never;
type N = GenericReturnType<number, <T>(item: T) => T[]>; // N = {}[]
as well as
type GenericReturnType<TGenericParameter, TFunction> = TFunction extends <T>(...args: any[]) => infer R ? R : never;
type N = GenericReturnType<number, <T>(item: T) => T[]>; // N = {}[]
and further tried
type GenericReturnType<TGenericParameter, TFunction> = TFunction extends <T extends TGenericParameter>(...args: any[]) => infer R ? R : never;
type N = GenericReturnType<number, <T>(item: T) => T[]>; // N = {}[]
also this
type GenericReturnType<TGenericParameter, TFunction> = TFunction extends (arg: TGenericParameter) => infer R ? R : never;
type N = GenericReturnType<number, <T>(item: T) => T[]>; // N = {}[]
as well as
type x = (<T>(item: T) => T[]) extends <T>(arg: T) => infer R ? R : never // x = {}[]
and lastly
type x = (<T>(item: T) => T[]) extends (arg: number) => infer R ? R : never // x = {}[]
However, none of them provide the desired type of number[]
Therefore, my query is, is there any method to develop something akin to the built-in ReturnType
that functions for functions with generic parameters, taking into account the types of said generic parameters? (or, a resolution to the issue presented above)