Get the resolved type of every promise in an object
Map over an object type of promises with Awaited to type what Promise.all gives back for each key. Works in TypeScript 4.5 and later.
You have { user: Promise<User>, count: Promise<number> } and want a function that awaits all of them and returns plain values.
type Resolved<T> = { [K in keyof T]: Awaited<T[K]> };
async function resolveAll<T extends Record<string, unknown>>(input: T): Promise<Resolved<T>> {
const entries = await Promise.all(
Object.entries(input).map(async ([key, value]) => [key, await value] as const),
);
return Object.fromEntries(entries) as Resolved<T>;
}
async function main(): Promise<void> {
const result = await resolveAll({
name: Promise.resolve('Ada'),
count: Promise.resolve(3),
flag: true,
});
console.log(result);
}
main();{ name: 'Ada', count: 3, flag: true }Awaited<T> unwraps promises, including nested ones, and leaves other types alone, so result.name is string, result.count is number and result.flag is boolean. It was added in TypeScript 4.5. The as Resolved<T> cast is needed because Object.fromEntries returns a loose type.
The promises run concurrently, since they were already started when passed in. If one rejects, Promise.all rejects with it and the others keep running, unobserved. Use Promise.allSettled when you need every result.