Typing async code and promises
Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.
What you will be able to do
#- Type async functions and awaited values.
- Use Awaited to unwrap nested promises.
- Type Promise.all and Promise.allSettled results.
Overview
#async functions
An async function always returns a Promise. The declared return type is the resolved value.
async function load(id: string): Promise<number> {
return 1;
}
await unwraps
await removes one Promise layer. Awaited<T> models that recursively.
type A = Awaited<Promise<Promise<string>>>; // string
Promise.all
Promise.all preserves tuple types.
const [a, b] = await Promise.all([Promise.resolve(1), Promise.resolve("x")]);
// a: number, b: string
With a plain array of promises, the result is T[].
Promise.allSettled
The result is an array of discriminated results, so you must check status.
const results = await Promise.allSettled([p1, p2]);
results.forEach((r) => {
if (r.status === "fulfilled") console.log(r.value);
else console.error(r.reason);
});
Errors
In strict mode a catch variable is unknown. Narrow it before use.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What is the type of `x`? ```ts async function f() { return 1; } const x = await f(); ```
Exercise 2Implement
Implement `loadAll<T>(loaders: readonly (() => Promise<T>)[]): Promise<T[]>` that runs them with Promise.all.
starter.typescriptexport function loadAll<T>(loaders: readonly (() => Promise<T>)[]): Promise<T[]> { // your code }Reveal the reference answer
reference.typescriptexport function loadAll<T>(loaders: readonly (() => Promise<T>)[]): Promise<T[]> { return Promise.all(loaders.map((load) => load())); }Authored expected output: Compiles with no errors. Runtime: loadAll([async () => 1, async () => 2]) resolves to [1, 2].
The generic T flows through the loader array into the resolved array type.
Exercise 3Debug
This fails under strict because the catch value is unknown. Fix it. ```ts try { await run(); } catch (error) { console.log(error.message); } ```
starter.typescripttry { await run(); } catch (error) { console.log(error.message); }Reveal the reference answer
reference.typescripttry { await run(); } catch (error) { if (error instanceof Error) console.log(error.message); }Authored expected output: Compile error resolved: 'error' is of type 'unknown'. Narrowing with error instanceof Error fixes it.
useUnknownInCatchVariables makes the catch binding unknown, so it must be narrowed.
Common misconceptions
#- An async function returns the value directly.
- Promise.all rejects with all errors.
- A catch variable is typed any by default in strict mode.
Follow-up practice
#- typescript-factories
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.