Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

You have { user: Promise<User>, count: Promise<number> } and want a function that awaits all of them and returns plain values.

resolve-all.tsTypeScript
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();
Text
{ 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.

Also inAsync
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.