Languages
[Edit]
EN

TypeScript - ReturnType<> with generic function

6 points
Created by:
evangeline
330

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
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