Sub topic 3
Catching Forgotten Awaits
Assume you know basic TypeScript types, generics, union narrowing, and JavaScript async/await.
Catching forgotten awaits
A promise is a value that will finish later. An async function always returns a Promise, even when its body returns an ordinary value. TypeScript checks the promise type, but it does not automatically reject every forgotten await.
async function save(): Promise<void> {
// persist data
}
function onClick(): void {
void save().catch((error: unknown) => {
console.error(error);
});
}The void marks that ignoring the returned promise is intentional. Configure a linter such as @typescript-eslint/no-floating-promises to find accidental floating promises. The TypeScript compiler alone usually cannot detect them.
Generic async helpers
A generic function preserves the type supplied by its caller. Put the type parameter on the promise returned by the helper.
async function withTimeout<T>(
task: Promise<T>,
milliseconds: number
): Promise<T> {
await new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
return await task;
}Here, withTimeout<number>(...) resolves to a number, while withTimeout<User>(...) resolves to a User. In production, a timeout helper should also reject or cancel the task; this small example demonstrates type preservation.
Modeling failure with a Result union
Thrown errors are not represented in a function's return type. A Result union makes success and failure explicit.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function attempt<T>(task: Promise<T>): Promise<Result<T>> {
try {
return { ok: true, value: await task };
} catch (error: unknown) {
return {
ok: false,
error: error instanceof Error ? error : new Error(String(error)),
};
}
}Check ok before reading value or error. This discriminated union lets TypeScript narrow each branch safely.
Cancellation with `AbortSignal`
Cancellation is separate from failure handling. Pass an AbortSignal to APIs that support it.
async function fetchText(
url: string,
signal?: AbortSignal
): Promise<string> {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.text();
}Async iterables and `for await`
An async generator produces values over time. for await consumes those values while preserving their type.
async function* pages(): AsyncGenerator<number[], void, undefined> {
yield [1, 2];
yield [3, 4];
}
async function total(): Promise<number> {
let result = 0;
for await (const page of pages()) {
result += page.reduce((sum, n) => sum + n, 0);
}
return result;
}Validating data at async boundaries
Parsed JSON is untrusted. as User only silences the compiler; it does not validate the response. Parse into unknown, then check its shape with a schema library or a type guard before using it.
Exercise
Why does await attempt(task) require checking result.ok before reading result.value?
Show answer
Result<T> is a union. The ok check narrows it to the success variant, where value exists.