Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript ReturnType with nested functions

Tags:

typescript

I'm trying to use ReturnType to generate a type that depends on the return types of functions living on an object.

Here is the object:

const foo = {
  bar: (): number => 1,
  quux: (): string => 'a',
};

The desired resulting type is:

type FooLeaves = {
  bar: number;
  quux: string;
};

Is it possible to apply a ResultType to the values of the object in order to pull the return types out of the nested functions?

I guess I could invoke each value and take the type of that, but it seems hacky

like image 453
sliptype Avatar asked Mar 03 '23 21:03

sliptype


1 Answers

It's pretty straightforward using mapped types:

type FooLeaves = { [K in keyof typeof foo]: ReturnType<typeof foo[K]> };

This is equivalent to

type FooLeaves = {
  bar: number;
  quux: string;
};

If you'd like a more generic solution, you might use conditional types to create something like this:

type ResultsOf<T> = { [K in keyof T]: T[K] extends (...args: any) => infer R ? R : T[K] }

This will also handle the cases where you mix functions and regular values, for example:

const foo = {
  bar: (): number => 1,
  quux: 'a',
};

type FooLeaves = ResultsOf<typeof foo>; // { bar: number, quux: string }
like image 53
p.s.w.g Avatar answered May 12 '23 05:05

p.s.w.g