The Analogy: The Sealed Tender Envelope at a Procurement Office
A council runs a sealed-bid tender for its contracts. Contractors post their bids, and what the clerk files on the day is not a bid anyone can read: it is a sealed envelope with a printed label on the outside stating which contract it is for and that a priced bid is inside. The label is real, the clerk can hold it, sort by it, and stack it, but the figures cannot be read through the paper. A Promise<Bid> is that envelope: the seal hides the value, and the <Bid> on the label states the type of what will be inside once the envelope is opened.
The rule of the tender is that no envelope is opened before the official opening session. Until then the clerk works only with the labels, filing each envelope, counting them, and checking each is for a real contract. That is all a Promise lets you do before you await it: pass it around, store it, drop it in a list, because the value inside is still sealed. Opening the envelope at the session is await: only then does the sealed Bid type become the plain bid inside, the figure you can finally read and act on.
The label is precise about what is inside, and that precision is worth deriving rather than re-writing by hand. If the office prints its labels from the very template it uses to draw up the bid, the label can never disagree with the contents. Deriving the expected type straight from the function that produces it, with Awaited<ReturnType<typeof fn>>, is the same discipline: change what goes into the envelope and the label follows automatically. An envelope that arrives sealed inside another envelope is opened straight through to the innermost bid in one motion, which is Awaited unwrapping a nested promise down to the value at the bottom.
The failure mode is treating the sealed envelope as though it were the bid. Sort the envelopes into "cheapest first" by weighing the paper and you have ranked nothing about the prices, because the figures are still sealed inside. A Promise used without await is exactly this: reading a field off it finds the envelope's own properties, never the bid's, so user.name does not exist on a Promise<User>. Worse, testing the envelope for truthiness always passes, because a sealed envelope is plainly a real object, so an "if the list came back empty" check written against the unopened promise is always true and its other branch never runs.
Syntax or Core Structure
The return type of an async function is always Promise<T>, where T is what it resolves to. You write Promise<number> even when the body returns a plain number, because the function wraps it for you.
// src/shapes.ts
async function answer(): Promise<number> {
return 42; // wrapped in a Promise automatically
}
async function label(n: number): Promise<string> {
return "n=" + n;
}
async function main(): Promise<void> {
console.log(await answer());
console.log(await label(7));
}
main();
Output:
42
n=7
answer returns 42, but because it is async its type is Promise<number>, not number; annotating it : number would be an error. label resolves to a string. Inside main, await answer() unwraps 42 and await label(7) unwraps "n=7", which print in order. A function that resolves with nothing uses Promise<void>, exactly as main does here.
Technical Depth: The Missing await, Awaited, and Deriving Types
Forgetting await gives back the envelope, Awaited unwraps a promise type even when nested, and Awaited<ReturnType<typeof fn>> derives a result type straight from its function.
The missing await, caught and silent
An async call without await yields a Promise, not the value. Sometimes the compiler catches the mistake when you read a field; sometimes it does not, because testing a Promise for truthiness is perfectly legal and always passes.
// src/missing.ts
interface User {
id: number;
name: string;
}
async function getUser(id: number): Promise<User> {
return { id, name: "user" + id };
}
async function main(): Promise<void> {
const claim = getUser(1); // Promise<User>, not User
console.log(typeof claim);
const user = await claim;
console.log(user.name);
if (claim) {
console.log("claim is truthy"); // always: a Promise is an object
}
}
main();
Output:
object
user1
claim is truthy
getUser(1) returns a Promise, so typeof claim is "object", the envelope, not the user. await claim unwraps it into user, and user.name is "user1". The if (claim) test always passes, because a Promise is a real object and every object is truthy, so a "did it come back empty" check written against the unopened promise never behaves as intended. The lint rules that flag a floating or misused promise exist precisely to catch this silent case.
Awaited unwraps, even when nested
The Awaited<T> utility type gives the value type a promise resolves to, and it unwraps recursively, so a promise of a promise flattens to the innermost value.
// src/awaited.ts
type Plain = Awaited<Promise<number>>; // number
type Deep = Awaited<Promise<Promise<string>>>; // string
async function main(): Promise<void> {
const a: Plain = 5;
const b: Deep = "ok";
console.log(a);
console.log(b);
}
main();
Output:
5
ok
Awaited<Promise<number>> is number, so a is a plain number holding 5. Awaited<Promise<Promise<string>>> unwraps both layers to string, so b is a plain string holding "ok". The recursion is why await on a doubly-wrapped promise gives the value at the bottom, and why applying Awaited to a value that was never a promise is harmless: it simply leaves the type as it is.
Deriving a result type from its function
The idiom you reach for daily is Awaited<ReturnType<typeof fn>>: it reads the async function's return type, which is a Promise<T>, and unwraps it to T, so you never hand-write the shape and it never drifts.
// src/derive.ts
async function loadDashboard() {
return { name: "ada", unread: 3 };
}
type Dashboard = Awaited<ReturnType<typeof loadDashboard>>;
function summarise(d: Dashboard): string {
return d.name + " has " + d.unread + " unread";
}
async function main(): Promise<void> {
const dash = await loadDashboard();
console.log(summarise(dash));
}
main();
Output:
ada has 3 unread
ReturnType<typeof loadDashboard> is Promise<{ name: string; unread: number }>, and wrapping it in Awaited strips the promise to give Dashboard. summarise takes that derived type, so await loadDashboard() produces a value it accepts directly, printing "ada has 3 unread". Add a field to loadDashboard and Dashboard gains it automatically; the type is printed from the same template as the value, so the label can never disagree with the contents.
Promise type reference
| Expression | Type |
|---|---|
| an async function returning 1 | a function giving Promise<number> |
| await a Promise<User> | User |
| Awaited of Promise<T> | T |
| Promise.resolve(1) | Promise<number> |
| ReturnType of an async function | Promise<T>, still wrapped |
The last row is the trap: ReturnType alone hands back the sealed envelope, still a Promise<T>. Wrap it in Awaited to get the letter inside.
Real World Example: A Generic Settle Wrapper
A batch of jobs each produce a number, but some fail. A generic settle runs each operation and substitutes a fallback when one rejects, so the batch always yields a full array of results. The single type parameter T means the wrapper knows nothing about jobs or prices, yet the caller keeps the exact number[] type back. The report prices a batch where one job fails.
// src/settle.ts
async function settle<T>(ops: (() => Promise<T>)[], fallback: T): Promise<T[]> {
const out: T[] = [];
for (const op of ops) {
try {
out.push(await op());
} catch {
out.push(fallback);
}
}
return out;
}
interface Job {
ref: string;
units: number;
ok: boolean;
}
function pad(text: string, width: number): string {
return text.padEnd(width);
}
const JOBS: Job[] = [
{ ref: "J1", units: 4, ok: true },
{ ref: "J2", units: 7, ok: false },
{ ref: "J3", units: 5, ok: true },
];
async function priceJob(job: Job): Promise<number> {
if (!job.ok) {
throw new Error("job failed: " + job.ref);
}
return job.units * 10;
}
async function main(): Promise<void> {
const ops = JOBS.map((j) => () => priceJob(j));
const prices = await settle(ops, 0);
const rows: string[] = [];
let total = 0;
for (let i = 0; i < JOBS.length; i++) {
const p = prices[i];
total += p;
rows.push(pad(JOBS[i].ref, 6) + pad(String(JOBS[i].units), 6) + String(p));
}
const report = [
"jobs: " + JOBS.length,
pad("JOB", 6) + pad("UNITS", 6) + "PRICE",
...rows,
"total: " + total,
];
console.log(report.join("\n"));
}
main();
Output:
jobs: 3
JOB UNITS PRICE
J1 4 40
J2 7 0
J3 5 50
total: 90
settle<T> is declared once with a type parameter, and calling it with number-producing operations and a fallback of 0 makes T become number, so prices is typed number[] with no annotation at the call site. The wrapper runs each operation in a try, catching any rejection and pushing the fallback instead, so it always returns as many results as there were operations. The generic preserves the caller's type end to end while hiding the catch-and-default machinery.
Trace the prices. J1 succeeds at 4 units times ten, which is 40. J2 has ok: false, so priceJob throws, the catch substitutes the fallback 0, and its row still shows its 7 units beside a price of 0. J3 succeeds at 5 times ten, which is 50. The total accumulates 40 + 0 + 50, which is 90, printed in the footer.
The design has real limits worth naming. The sharpest flaw is that settle swallows the failure entirely: a rejected job becomes a 0-priced row indistinguishable from a job that genuinely costs nothing, so the total is quietly wrong and no record survives of which job failed or why. A sounder design would resolve each entry to a tagged result, an ok-or-error shape the caller inspects, rather than a bare value that hides the difference. The second limit is that settle awaits its operations one at a time in the for loop, so independent jobs run in sequence rather than overlapping; a version built on Promise.allSettled would run them concurrently and still capture every outcome. A fallback keeps a batch running, but a silent fallback trades a loud failure for a wrong number.
Common Mistakes
- Forgetting await and reading a field. Accessing a property on the result of an async call without
awaitreads the Promise object, not the value, so the field does not exist. The compiler usually catches this one; add theawait.
- Testing an unawaited promise for truthiness. A Promise is always a truthy object, so
if (getList())always takes the true branch. This compiles silently, so lint for floating and misused promises to catch it.
- Annotating an async function with the plain type. Writing
: Userinstead of: Promise<User>on anasyncfunction is an error, because the function's real return is always wrapped in a Promise.
- Double-wrapping the annotation. Declaring
Promise<Promise<T>>is wrong even thoughAwaitedwould flatten it; an async function that returns aThas the typePromise<T>, with a single layer.
- Trusting res.json() as a typed value. A JSON parse resolves to
anyorunknown, so asserting itas Promise<User>is a claim with nothing behind it. Treat the result asunknownand validate it before use.
- Using ReturnType without Awaited.
ReturnType<typeof asyncFn>is still thePromise<T>envelope; deriving the value type needsAwaited<ReturnType<typeof asyncFn>>, or the downstream type stays wrapped.
- Passing an async callback where a sync one is expected.
arr.filter(async x => ...)filters on the returned promises, which are all truthy, so nothing is filtered out. Array predicate callbacks must be synchronous.
- Confusing Promise<void> with Promise<undefined>. Use
Promise<void>for an operation whose resolved value is not meant to be used;Promise<undefined>claims the value is a meaningfulundefined, which is rarely intended.
- Swallowing a rejection into a silent default. Catching an error and substituting a fallback with no record turns a loud failure into a quietly wrong result. Return a tagged outcome the caller can inspect instead.
Best Practices
- Annotate the return type of every exported async function. Writing
Promise<T>explicitly documents the contract and stops inference from drifting as the body changes.
- Derive result types with Awaited and ReturnType. Use
Awaited<ReturnType<typeof fn>>rather than re-declaring an async function's result shape, so the type follows the function automatically.
- Prefer async and await over then chains. Narrowing,
try/catch, and stack traces all work better withawaitthan with a chain of.thencallbacks.
- Lint for floating and misused promises. Enable the rules that flag an unawaited promise and a promise passed where a value is expected, because those are the failures the compiler alone will not catch.
- Keep array predicate callbacks synchronous. Never hand an
asynccallback tofilter,mapused as a guard, or similar, since the returned promises are all truthy and defeat the check.
- Use Promise<void> for fire-and-complete work. Reserve
Promise<void>for operations whose value is not meant to be read, and return the created entity instead when the caller will need it.
- Validate what a promise resolves to at a boundary. Type an external result as
unknownand run it through a guard rather than asserting a shape onto aPromise<any>that nothing has checked.
- Return a tagged outcome instead of a silent fallback. When an operation can fail, resolve to an ok-or-error result the caller inspects, so a failure is visible rather than hidden behind a default value.
Practice Exercises
- The sealed envelope. Write
async function fetchTitle(url: string): Promise<string>, call it withoutawaitand try to call.toUpperCase()on the result, read the error, then fix it withawait.
- The derived type. Write an async
loadProfile()that returns an object with three fields, declaretype Profile = Awaited<ReturnType<typeof loadProfile>>, and useProfileas a function parameter without hand-writing the shape.
- The generic preserved. Give
settlefrom the lesson a set of string-producing operations and a string fallback, and confirm the result is typedstring[]with no annotation at the call site.
- The tagged outcome. Rewrite
settleso each entry resolves to an ok-or-error object rather than a bare value or fallback, then show that a failed job is now distinguishable from a genuinely zero one in the report.