Sub topic 8
Writing Generic Async Helpers
Assume you know basic TypeScript types, generics, unions, and async/await. A generic async helper is a reusable function whose input and resolved output types are connected by a type parameter.
The goal is to preserve useful type information. A helper should not turn every result into unknown, any, or a broad object type.
Connect the input and output types
Suppose a helper applies an asynchronous function to every item in an array. The item type and result type are different, so use two type parameters:
async function mapAsync<T, U>(
items: readonly T[],
transform: (item: T, index: number) => PromiseLike<U> | U,
): Promise<U[]> {
return Promise.all(items.map(transform));
}
async function main(): Promise<void> {
const lengths = await mapAsync(
["Ada", "Grace", "Linus"],
async (name) => name.length,
);
const labels = await mapAsync(
[1, 2, 3],
(value) => `item-${value}`,
);
console.log(lengths); // [3, 5, 5]
console.log(labels); // ["item-1", "item-2", "item-3"]
}
void main();TypeScript infers T from items and U from the transform function:
| Input | Transform result | Resolved helper type |
|---|---|---|
| `string[]` | `Promise<number>` | `Promise<number[]>` |
PromiseLike<U> accepts both a real promise and promise-compatible objects. Including U also permits a synchronous transform. If your codebase wants to require asynchronous callbacks, use only Promise<U>.
Promise.all preserves the order of the input array. It also unwraps each promise, so the helper returns U[], not Promise<U[]> inside another promise.
Preserve resolved types with `Awaited`
When a helper accepts values that might already be promises, Awaited<T> describes the type after promise-like layers are removed.
async function unwrap<T>(value: T): Promise<Awaited<T>> {
return await value;
}
async function example(): Promise<void> {
const numberValue = await unwrap(42);
const textValue = await unwrap(Promise.resolve("ready"));
// numberValue is number
// textValue is string
console.log(numberValue, textValue);
}
void example();Awaited<T> handles nested promise-like values recursively. It is useful when a helper’s input can be either immediate or delayed.
A common mistake is writing a generic return type that repeats information incorrectly:
async function wrong<T>(value: T): Promise<T> {
return await value;
}This works for ordinary values, but it becomes misleading when T itself is a promise. Prefer Promise<Awaited<T>> when the helper resolves its input before returning.
Generic helpers do not validate data
Generics describe relationships known at compile time. They do not inspect values at runtime. This helper is unsafe:
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return (await response.json()) as T;
}The caller can request any type, even when the server returns something else. An assertion changes the compiler’s belief but does not validate the response.
A safer design accepts a parser or validator:
type Parser<T> = (value: unknown) => T;
async function fetchParsed<T>(
url: string,
parse: Parser<T>,
): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const raw: unknown = await response.json();
return parse(raw);
}
function parseUser(value: unknown): { id: number; name: string } {
if (
typeof value !== "object" ||
value === null ||
!("id" in value) ||
!("name" in value) ||
typeof value.id !== "number" ||
typeof value.name !== "string"
) {
throw new Error("Invalid user response");
}
return { id: value.id, name: value.name };
}Here, T connects the parser’s output to the promise’s resolved type. The parser performs the runtime check that TypeScript cannot perform.
Exercise
Exercise
What is the resolved type of await mapAsync([1, 2], async (n) => n.toString()), and why?
Show answer
It is string[]. TypeScript infers T as number from the input and U as string from the transform result.