Callbacks
| Callback types | |
| Inline anonymous | |
| Named handlers | |
| Flatten nesting |
Callback types
A callback is a function passed into another function to run later. Its type lists parameter types and the return type in one arrow shape. Writing the shape once keeps every caller and every handler in agreement.
type Done = (ok: boolean) => void;
function run(done: Done): void {
done(true);
}
Inline anonymous
Short one off handlers read best written inline at the call site. The arrow sits exactly where it runs. Extract the handler only when it grows or earns reuse.
const nums: number[] = [1, 2, 3];
nums.forEach((n) => {
console.log(n);
});
Named handlers
A named handler gives the callback a clear purpose and a testable home. Define it once with full annotations, then pass it by name. Stack traces and error messages also become far easier to read.
function handleNumber(n: number): void {
console.log(n);
}
const nums: number[] = [1, 2, 3];
nums.forEach(handleNumber);
Flatten nesting
Nested callbacks pile indentation and hide the happy path. Named steps, early returns, and promise chains restore a flat top to bottom flow. Read the result as a list of stages, not a staircase.
function stepOne(): Promise<number> {
return Promise.resolve(1);
}
stepOne()
.then((n) => n + 1)
.then((n) => {
console.log(n);
});
Next: Narrowing
Article author: Arthur Isaev