How do I get the return type of a function in a stream?

In this example:

const myObj = {
    test: true,
};

type MyType = typeof myObj;

const getValue = (): MyType => {
    return myObj;
};

// how to do this??
type TheReturnType = getValue;

const nextObj: TheReturnType = {
    test: false,
};

      

I would like to extract type

what the function will return, so I can reuse that type. I don't think this is impossible. The above doesn't work. typeof getValue

will return a function.

+3


source to share


1 answer


Here's a helper ExtractReturn

that can capture the return type of a function:

type ExtractReturn<F> =
  $PropertyType<$ObjMap<{ x: F }, <R>(f: () => R) => R>, 'x'>

      

Use this:

type TheReturnType = ExtractReturn<typeof getValue>

      

TheReturnType

Will now have the return type of a function getValue

. Also note that calling a helper ExtractReturn

requires a statement typeof

before the function name.




Here's a completely different way to implement the helper ExtractReturn

:

type _ExtractReturn<B, F: (...args: any[]) => B> = B;
type ExtractReturn<F> = _ExtractReturn<*, F>;

      

This helper works exactly the same as above; The point is, there is more than one way to accomplish this.

+1


source







All Articles