Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a function's return type in flow?

Tags:

flowtype

With 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'd like to extract the type that the function will return, so I can reuse that type. I can think of no way to get it. The above doesn't work. typeof getValue will return the function.

like image 958
Laurens Kling Avatar asked Jun 22 '17 13:06

Laurens Kling


1 Answers

Flow has a $Call utility type, which can get a function's return type:

type TheReturnType = $Call<typeof getValue>

However, if your function takes arguments, you need to provide types for those as well:

type TimeoutType = $Call<typeof setTimeout, () => void, number>

If that seems inconvenient, you can write a ReturnType helper that can skip the need for arguments:

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

Let's use this:

type TheReturnType = ReturnType<typeof setTimeout>

This ReturnType helper basically matches the ReturnType helper present in TypeScript.

like image 107
William Swanson Avatar answered Sep 21 '22 03:09

William Swanson