Promises
A promise is a value that will be available later. In TypeScript it is also a type with one
parameter: Promise<T> fulfils with T. What the type cannot express is when or whether it will
settle, which is where the interesting bugs live.
The 60-second answer
Section titled “The 60-second answer”“A Promise<T> is pending, fulfilled with T, or rejected with a reason typed as unknown. then
maps a fulfilment value and returns a new promise, catch handles a rejection, finally runs on
both paths without changing the result. async functions always return a promise, and await unwraps
one level and throws on rejection, which is why try/catch works. Promise.all requires all
results, allSettled tolerates failures, race takes the first to settle and any the first to
succeed. The type system tracks the value type but not the sequencing, the cancellation, or the error
type unless you annotate it.”
The states
Section titled “The states”type FetchState<T> = | { status: 'pending' } | { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown };A promise object exposes only then, catch and finally — there is no .state or .value
property. Reading the result requires a continuation, which is the point: the value is only safe to
use inside a handler. Promise<T> is covariant in T, so a Promise<string> is assignable to a
Promise<string | number>; that is fine for reading and irrelevant when you accumulate into arrays.
then, catch, finally
Section titled “then, catch, finally”interface User { id: string; name: string }
fetch('/api/user/1') .then((res) => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json() as Promise<User>; // returning a promise flattens it }) .then((user) => user.name) .catch((err: unknown) => (err instanceof Error ? err.message : 'unknown error')) .finally(() => console.log('settled'));Typing notes:
thenis generic:.then<U>(fn: (value: T) => U | PromiseLike<U>)returnsPromise<U>, so the chain type is derived and intermediate annotations are usually unnecessary.- A
catchcallback receivesunknownunderstrict, which forces a check before.message. finallytakes no value and returnsPromise<T>; it cannot change the result unless it throws..json()in the DOM lib returnsPromise<any>. Assert or, better, validate. The cast is a claim the compiler cannot verify.
Combinators, typed
Section titled “Combinators, typed”const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]); // [User, Post[]]
const settled = await Promise.allSettled([fetchUser(), fetchPosts()]);for (const r of settled) { if (r.status === 'fulfilled') console.log(r.value); else console.error(r.reason);}
const fastest = await Promise.any([mirrorA(), mirrorB()]); // User| Method | Resolved type | Rejects with |
|---|---|---|
Promise.all |
Tuple or T[] |
First rejection reason |
Promise.allSettled |
PromiseSettledResult<T>[] |
Never |
Promise.race |
Union of all types | First settled, either way |
Promise.any |
Union of all types | AggregateError |
Promise.all on a tuple preserves positions, which is why destructuring works without casts. Pass a
non-tuple array and you get (A | B)[]. Promise.any’s AggregateError carries each reason in
.errors; the type models it as a plain error, so narrow at runtime.
async/await and typing
Section titled “async/await and typing”async function loadUser(id: string): Promise<User> { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new HttpError(res.status); return (await res.json()) as User;}
async function loadAll(ids: string[]): Promise<User[]> { return Promise.all(ids.map(loadUser));}async wraps a returned value in a promise and converts a thrown error into a rejection. Returning a
promise from an async function flattens it, so Promise<Promise<T>> never materialises. Awaited<T>
unwraps nested promises and is the right tool in generic helpers.
Common mistakes
Section titled “Common mistakes”fetch('/api/save', { method: 'POST' }); // 1. floating promise: errors escape
for (const id of ids) await loadUser(id); // 2. sequential where parallel is possible
ids.forEach(async (id) => { await loadUser(id); }); // 3. forEach ignores the promise
try { fetch('/api/x'); } catch { /* never runs */ } // 4. catch around an unawaited promise
catch (e) { e.message; } // 5. error: 'e' is unknown
new Promise((resolve) => resolve(fetchUser())); // 6. wrapping an existing promiseTurn on no-floating-promises and no-misused-promises in typescript-eslint. They catch most of the
above, which the type system itself cannot.
Follow-up questions
Section titled “Follow-up questions”- Why does
res.json()returnPromise<any>, and what should you do about it? - What is the difference between
Promise<void>andvoid? - Why is
Promise<T>covariant, and where does that bite? - How do you type the rejection reason when
unknownis not enough?
Common traps
Section titled “Common traps”- Assuming the type guarantees success.
Promise<User>says nothing about HTTP status;fetchresolves on 404 and 500 too. - Not checking
res.ok. The most common bug in typed fetch wrappers. asinstead of validation. The cast is erased; the data is not what you claimed.awaitinmapwithoutPromise.all. You get an array of promises, not of values.- Catching
unknownand calling.message. Narrow withinstanceof Errorfirst. - Using
Promise.raceas a timeout without cancelling. The loser keeps running.