Sub topic 8
Writing generic async helpers
This chapter assumes you know generics at the level of Array<T>, how async/await works, and the Promise<T> and Awaited<T> types from earlier chapters. All examples assume "strict": true in tsconfig.json.
Why helpers need generics
Most async code repeats the same wrapping logic: add a timeout, retry on failure, limit concurrency, log timing. The wrapping logic does not care what the wrapped operation returns. If you write the helper with Promise<unknown> or Promise<any>, every caller loses the resolved type. A generic helper keeps the type, so the caller still gets string from a Promise<string>.
The rule is simple. If a helper hands back a value that came from the caller's promise, the helper's signature should connect the two with a type parameter.
The basic shape: Promise<T> in, Promise<T> out
The smallest useful helper takes a promise and returns a promise of the same type. This one rejects if the promise takes too long.
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`Timed out after ${ms} ms`));
}, ms);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
(error: unknown) => {
clearTimeout(timer);
reject(error);
},
);
});
}
const slow = new Promise<string>((resolve) => {
setTimeout(() => resolve("done"), 50);
});
withTimeout(slow, 1000).then((text) => {
console.log(text.toUpperCase()); // text is string
});TypeScript infers T = string from the argument. You never write withTimeout<string>. Inference works because T appears in a parameter position, and the compiler matches Promise<string> against Promise<T>.
Two details matter here:
- The helper uses
new Promise<T>(...)with an explicit type argument. Without it, the constructor would inferPromise<unknown>andresolve(value)would still compile, but the return type would not match. - The rejection handler declares
error: unknown. A promise rejection can carry any value, sounknownis the honest type.
This version does not cancel the underlying work when the timer fires. It only stops waiting. The cancellation chapter covers AbortSignal for stopping real work.
Inferring T from a callback
Often a helper receives a function that produces the promise, because the helper must be able to call it more than once. Retry is the standard case.
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}
interface RetryOptions {
attempts: number;
delayMs?: number;
}
async function retry<T>(
fn: (attempt: number) => Promise<T>,
options: RetryOptions,
): Promise<T> {
if (options.attempts < 1) {
throw new RangeError("attempts must be at least 1");
}
let lastError: unknown;
for (let attempt = 1; attempt <= options.attempts; attempt++) {
try {
return await fn(attempt);
} catch (err) {
lastError = err;
if (attempt < options.attempts && options.delayMs) {
await delay(options.delayMs);
}
}
}
throw lastError;
}
async function flaky(attempt: number): Promise<number> {
if (attempt < 3) {
throw new Error("not yet");
}
return attempt * 10;
}
retry(flaky, { attempts: 5, delayMs: 10 }).then((n) => {
console.log(n.toFixed(1)); // n is number, prints 30.0
});Here T is inferred from the callback's return type. flaky returns Promise<number>, so T is number. The lastError: unknown variable matches the rule from the error-handling chapter: you keep the thrown value as unknown and decide later how to narrow it.
What happens when the callback returns a union
If the callback can return different shapes, T becomes the union.
async function maybeNumber(): Promise<number | null> {
return Math.random() > 0.5 ? 1 : null;
}
async function demo(): Promise<void> {
const value = await retry(() => maybeNumber(), { attempts: 2 });
// value is number | null, so narrow it before use
if (value !== null) {
console.log(value + 1);
}
}The helper does not add or remove cases. It passes the type through unchanged, which is the goal.
Accepting values or promises
Some helpers are friendlier if the caller can pass either a plain value or a promise. The usual parameter type is T | PromiseLike<T>. PromiseLike<T> accepts any thenable, not just the built-in Promise.
The return type needs care. If T is itself a promise type, Promise<T> would be a promise of a promise, which JavaScript never produces at runtime because promises flatten. Use Awaited<T> to describe what you really get.
function lift<T>(value: T | PromiseLike<T>): Promise<Awaited<T>> {
return Promise.resolve(value);
}
const a = lift(5); // Promise<number>
const b = lift(Promise.resolve("x")); // Promise<string>The standard library's Promise.resolve has the same signature, which is why this compiles without a cast.
The same issue appears when a caller passes an explicit type argument. retry<Promise<number>>(...) is legal, and T would be Promise<number>, but the real result is a plain number at runtime. Declare helpers so callers rarely need explicit arguments. When a generic function's result comes from awaiting T, write Promise<Awaited<T>>.
| Situation | Parameter type | Return type | Column |
|---|---|---|---|
| Caller always passes a promise | `Promise<T>` | `Promise<T>` | |
| Caller passes a function returning a promise | `() => Promise<T>` | `Promise<T>` | |
| Caller may pass a value or a thenable | `T \ | PromiseLike<T>` | `Promise<Awaited<T>>` |
| Caller passes a function that may be sync or async | `() => T \ | PromiseLike<T>` | `Promise<Awaited<T>>` |
Preserving argument types with tuple parameters
A decorator wraps a function and returns a function with the same signature. To keep the parameter list, capture it as a type parameter constrained to an array type.
function timed<A extends unknown[], R>(
fn: (...args: A) => Promise<R>,
): (...args: A) => Promise<R> {
return async (...args: A): Promise<R> => {
const start = performance.now();
try {
return await fn(...args);
} finally {
const elapsed = Math.round(performance.now() - start);
console.log(`took ${elapsed} ms`);
}
};
}
async function repeatText(text: string, times: number): Promise<string> {
return text.repeat(times);
}
const timedRepeat = timed(repeatText);
// (text: string, times: number) => Promise<string>
timedRepeat("ab", 3).then(console.log);A extends unknown[] makes A a tuple type, so (...args: A) keeps names, count, and order of the original parameters. The compiler will reject timedRepeat("ab") and timedRepeat(3, "ab").
You could write the same thing with Parameters<F> and ReturnType<F> on a single F extends (...args: never[]) => Promise<unknown>. That works, but the two-parameter form reads better and avoids Awaited<ReturnType<F>> in the body.
A concurrency limiter
Promise.all(items.map(fn)) starts every call at once. For hundreds of requests, you often want a cap. A generic mapLimit keeps the input and output types separate with two parameters, T for the item and U for the result.
async function mapLimit<T, U>(
items: readonly T[],
limit: number,
fn: (item: T, index: number) => Promise<U>,
): Promise<U[]> {
if (!Number.isInteger(limit) || limit < 1) {
throw new RangeError("limit must be a positive integer");
}
const results: U[] = [];
let next = 0;
async function worker(): Promise<void> {
while (next < items.length) {
const index = next;
next += 1;
results[index] = await fn(items[index], index);
}
}
const workerCount = Math.min(limit, items.length);
const workers = Array.from({ length: workerCount }, () => worker());
await Promise.all(workers);
return results;
}
async function square(n: number): Promise<number> {
await delay(5);
return n * n;
}
mapLimit([1, 2, 3, 4, 5], 2, square).then((values) => {
console.log(values); // [1, 4, 9, 16, 25]
});The workers share the next counter. JavaScript runs one piece of code at a time, so reading and incrementing next with no await between the two lines is safe. Results land at their original index, so the output order matches the input order even though the calls finish in a different order.
If any call rejects, Promise.all rejects right away, but the other workers keep running until their current call finishes. The helper does not stop them from starting new items either. If you need "stop on first failure", add a shared failed flag that the while loop checks.
Constraints and when not to be generic
A type parameter earns its place only when it links two positions in the signature. Compare these:
// Useful: T links the input callback and the output
function first<T>(fn: () => Promise<T>): Promise<T> {
return fn();
}
// Pointless: T appears once, so it behaves like unknown
function ignore<T>(promise: Promise<T>): Promise<void> {
return promise.then(() => undefined);
}In ignore, T appears only once, so you can write Promise<unknown> and lose nothing. The simpler signature is easier to read.
Use constraints when the helper needs to read something from the value:
async function pluckIds<T extends { id: number }>(
load: () => Promise<T[]>,
): Promise<number[]> {
const items = await load();
return items.map((item) => item.id);
}The constraint { id: number } lets the body read id. Callers can still pass richer item types, and nothing is thrown away on the input side.
Common errors
- Using
anyto "make it compile".Promise<any>turns off checking for every caller. Preferunknownfor values you do not inspect, or a type parameter for values you pass through. - Casting the result. Code such as
return (await fn()) as Tis a sign that the signature does not connect input and output. Fix the signature rather than the body. - Forgetting that a rejection is
unknown. Handlers like.catch((e) => e.message)compile only ifeisany. Annotatee: unknownand narrow. - Explicit partial type arguments. TypeScript does not allow giving some type arguments and inferring others. If you call
mapLimit<number>(...)with two type parameters, the compiler reports an error. Either pass both or none. - Async callbacks that return nothing. If
fnreturnsPromise<void>, thenTisvoid. That is valid, butawait retry(...)then yieldsvoid, which you cannot use in an expression.
Exercise
Write the signature (not the body) of a helper tap that takes a promise of any type T and a side-effect function (value: T) => void, runs the side effect when the promise resolves, and returns a promise of the same T. Then say what type x has in const x = await tap(Promise.resolve([1, 2]), (v) => console.log(v.length));.
Show answer
function tap<T>(promise: Promise<T>, effect: (value: T) => void): Promise<T>. T is inferred as number[] from the first argument, which also types v in the callback, so x is number[].
Exercise
A teammate writes async function race2<T>(a: Promise<T>, b: Promise<T>): Promise<T> { return Promise.race([a, b]); } and finds that race2(Promise.resolve(1), Promise.resolve("x")) fails to compile. Explain why, and show a signature that accepts both promises and returns the right union.
Show answer
One type parameter T must fit both arguments, and number and string give the compiler two conflicting candidates, so inference fails. Use two parameters: function race2<A, B>(a: Promise<A>, b: Promise<B>): Promise<A | B> { return Promise.race([a, b]); }. The result is Promise<number | string> for the example call.