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"]>
CodePudding user response:
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).