EN
TypeScript - ReturnType<> with generic function
6
points
In this short aritcle we would like to show you how to get result type from generic function in TypeScript.
Problem description:
typeof
operator was created to work with variables in runtime mode
e. g.typeof myFunction
,- when
myFunction
is generic it is not posible to dotypeof myFunction<Type>
operation, becausemyFunction<Type>
doesnt exists in the application memory - check below example to see some trick.
Quick solution:
// ----------------------------------------------------------------------------
// Genric function definition:
const createCollection = <T extends unknown> (...users: T[]) => {
return {
getUser: (index: number): T | null => {
return users[index] ?? null;
}
};
};
// ----------------------------------------------------------------------------
// Return type extracting:
class Wrapper<T extends unknown> {
//HINT: do not forget to match arguments to your function
mediate = (...args: any[]) => createCollection<T>(...args);
}
type GenericCollectionReturnType<T extends unknown> = ReturnType<Wrapper<T>['mediate']>;
// ----------------------------------------------------------------------------
// Type usage example:
const users: GenericCollectionReturnType<string> = createCollection('John', 'Kate');
console.log(users.getUser(0)); // John
console.log(users.getUser(1)); // Kate
Screenshot: