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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With