Reputation: 6186
I have an TypeScript object whose properties contain another object which all contain function properties. i.e. it conforms to this interface:
interface ObjectOfFunctions {
[key: string]: Function;
}
interface ObjectOfObjectsOfFunctions {
[key: string]: ObjectOfFunctions;
}
I'm trying to create a type that expresses the union of all of the return types of those inner functions.
I've managed to get it working for a single object, using the following:
export type PropertyReturnTypes<T> = T[keyof T] extends ((a: any) => any) ? ReturnType<T[keyof T]> : never;
But I can't figure out how to make it work with the outermost object (ObjectOfObjectsOfFunctions
). Can someone help me with this?
Upvotes: 0
Views: 80
Reputation: 249666
If you are trying to get the return type of all nested function, one level deep, you can use a mapped type to get all the types return types for each nested objects using your ObjectOfFunctions
type. You can then get a union of all of these types using another indexing operation:
export type PropertyReturnTypes<T> = T[keyof T] extends ((a: any) => any) ? ReturnType<T[keyof T]> : never;
export type NestedPropertyReturnTypes<T> = {
[P in keyof T]: PropertyReturnTypes<T[P]>
}[keyof T];
type R = NestedPropertyReturnTypes<{
o: {
f1: () => "f1"
f2: () => "f2"
},
o2: {
f2: () => "f2"
f3: () => "f3"
},
}>
// Same as
// type R = "f1" | "f2" | "f3"
Upvotes: 2