user5234194
user5234194

Reputation:

Map dynamically all types of functions in object

How to extract all function return types

const t = {
    fn1: a => ({test1: 1}),
    fn2: b => ({test2: 1}),
    fn3: c => ({test3: 1}),
}

let a: ReturnType<typeof t["fn1"]> | ReturnType<typeof t["fn2"]> | ReturnType<typeof t["fn3"]>;
//or
let b: ReturnType<typeof t["fn1"] |  typeof t["fn2"] | typeof t["fn3"]>;

Is it possible to map dynamically all types of fn1, fn2... into a one type? So get rid of that ReturnType<typeof t["fn1"]> | ReturnType<typeof t["fn2"]>

Upvotes: 0

Views: 62

Answers (1)

Terry
Terry

Reputation: 66228

You can dynamically map it by simply using the keyof typeof t to access all possible keys of t, i.e.:

let a: ReturnType<typeof t[keyof typeof t]>;

This will cause the type to be inferred as:

let a: {
    test1: number;
} | {
    test2: number;
} | {
    test3: number;
}

See proof-of-concept on TypeScript playground (I have removed the unused parameters a, b and c for demo purposes).

Upvotes: 2

Related Questions