Languages
[Edit]
EN

TypeScript - ReturnType<> with generic function

6 points
Created by:
evangeline
420

In this short aritcle we would like to show you how to get result type from generic function in TypeScript.

Problem description:

  1. typeof operator was created to work with variables in runtime mode
    e. g. typeof myFunction,
  2. when myFunction is generic it is not posible to do typeof myFunction<Type> operation, because myFunction<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:

TypeScript - ReturnType<> with generic function
TypeScript - ReturnType<> with generic function

Alternative titles

  1. TypeScript - return type with generic function
  2. TypeScript - return type with generic arrow function
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join