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