Barguast
Barguast

Reputation: 6186

Union of return types within nested objects

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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"

play

Upvotes: 2

Related Questions