Lesson 38 of 50TypeScript
Typing Functions
Type parameters, returns, callbacks, overloads, higher-order wrappers, this, assertion functions and async callbacks without floating promises.
Functions are the boundaries of your code: where one module hands data to another. Typing them well means every caller gets checked automatically, and bugs show up at the call site instead of three files away. This lesson covers everything you need to type the functions you write every day, including the callbacks you pass to map, addEventListener and React props.
Parameters and return types
Annotate each parameter after its name and the return type after the parameter list. Arrow functions use the same syntax.
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;Parameters must be annotated (otherwise they are implicitly any, which strict mode reports as an error). Return types are inferred, but writing them on exported functions is a good habit: if the body accidentally returns the wrong thing, the error appears inside the function, where the bug is.
function getDiscount(code: string): number {
if (code === "WELCOME") return 0.1;
// Error: Function lacks ending return statement and return type does not include 'undefined'.
}Each parameter gets a type. ? marks one as optional.
Optional and default parameters
A ? after a parameter name makes it optional: callers may leave it out, and inside the function its type includes undefined. A default value also makes it optional, and TypeScript infers the type from the default.
Press Run (⌘ Enter) to see what happens.Optional parameters must come after required ones. For functions with many options, prefer a single options object: call sites are readable and order stops mattering.
function fetchUsers(options: { page?: number; limit?: number; sort?: "name" | "date" } = {}) {
const { page = 1, limit = 20 } = options;
// ...
}
fetchUsers({ limit: 50 });function log(level?: string, message: string) {}Function types and callbacks
A function's type is written like an arrow: (params) => ReturnType. You use it to type callbacks and to store functions in variables.
type Comparator = (a: number, b: number) => number;
const ascending: Comparator = (a, b) => a - b; // a and b are inferred as numberThat last line shows contextual typing: when TypeScript knows what function type is expected, it types the parameters for you. It is why you rarely annotate callbacks to map or filter.
Press Run (⌘ Enter) to see what happens.Parameter names in a function type are just documentation. What matters is position and type. A callback is also allowed to take fewer parameters than the type offers, which is why arr.forEach((x) => ...) works even though forEach passes three arguments.
void vs undefined
A return type of void means "the caller should not use the return value". It is the right type for event handlers and callbacks that only cause side effects.
function logClick(event: { x: number; y: number }): void {
console.log(event.x, event.y);
}There is a subtle rule: a function type returning void accepts functions that return something. That is deliberate, so this works:
const ids: number[] = [];
[1, 2, 3].forEach((n) => ids.push(n)); // push returns a number, forEach expects void: OKundefined as a return type is stricter: the function must actually return undefined. Use void for "nothing useful", and T | undefined for "maybe a value".
type Handler = () => void; const h: Handler = () => 42;
Overloads
Sometimes the return type depends on the arguments. Overloads list several call signatures above one implementation. Callers see only the signatures, and the implementation must handle all of them.
function parseDate(timestamp: number): Date;
function parseDate(isoString: string): Date;
function parseDate(year: number, month: number, day: number): Date;
function parseDate(a: number | string, month?: number, day?: number): Date {
if (typeof a === "string") return new Date(a);
if (month !== undefined && day !== undefined) return new Date(a, month - 1, day);
return new Date(a);
}
parseDate("2026-03-01"); // OK
parseDate(2026, 3, 1); // OK
parseDate(2026, 3);
// Error: No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.Overloads are mostly for library authors. In your own code, a union parameter or two separate functions (parseIsoDate, dateFromParts) is usually clearer.
this parameters, briefly
In a regular function, you can declare what this must be as a fake first parameter. It is erased at compile time and only exists for checking.
function handleClick(this: HTMLButtonElement, event: MouseEvent) {
this.disabled = true;
}You will rarely need it: arrow functions and classes cover most cases.
Higher-order functions with generics
A higher-order function takes a function or returns one. At work they are everywhere: retry wrappers, timing and logging wrappers, debounce, memoize, middleware, and React's useCallback. The typing challenge is always the same: the wrapped function should keep the exact parameters and return type of the original, so callers lose nothing.
The trick is to capture the parameters as a tuple type parameter, A extends unknown[], and the result as R:
Press Run (⌘ Enter) to see what happens.Hover over loadInvoiceSafely in an editor and you see the original parameter names, not just their types. Tuple inference keeps the labels, which is a big readability win over typing the wrapper as (...args: any[]) => any. That shortcut compiles too, but every caller of the wrapped function silently loses checking.
Two details worth knowing. First, A extends unknown[], not any[]: the constraint only has to accept tuples, and unknown[] does. (Constructors were different, as you saw in Utility types: there the constraint was a whole constructor type, and a constructor that needs a string cannot stand in for one that accepts unknown. Here the constraint is on the tuple of arguments itself, and every tuple fits unknown[].) Second, sometimes a parameter should not be used for inference. In this state machine helper, initial must be one of the listed states, but by default TypeScript happily widens S to include it:
function createMachine<S extends string>(states: S[], initial: NoInfer<S>) {
return { states, initial };
}
createMachine(["idle", "loading"], "done");
// Error: Argument of type '"done"' is not assignable to parameter of type '"idle" | "loading"'.Without NoInfer (added in TypeScript 5.4), S would be inferred from both arguments as "idle" | "loading" | "done", and the typo would compile. NoInfer<S> says "check this argument against S, but do not learn S from it".
this in callbacks and ThisParameterType
The most common runtime this bug is a detached method: you pass obj.method somewhere as a callback, and when it is called, this is no longer obj.
Press Run (⌘ Enter) to see what happens.Class bodies are strict mode, so a detached method gets this === undefined and throws a TypeError on this.count. The arrow function field captured this when the instance was built, so it keeps working. Notice that TypeScript did not complain about either line. By default it does not track which methods use this.
You can make it track. Declare this explicitly on the method, and TypeScript checks every call:
class Timer {
ticks = 0;
tick(this: Timer) { this.ticks++; }
}
const tick = new Timer().tick;
tick();
// Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Timer'.The protection is only as good as the callback types on the other side. A callback type that says this: void, such as (this: void) => void, rejects Timer.prototype.tick. Many callback types, including setTimeout's, do not say anything about this, so a detached method still slips through. In practice teams turn on the typescript-eslint rule unbound-method, which flags passing a method that uses this without binding it. The fixes are the ones from the run above: an arrow function field, .bind(obj), or a wrapper () => obj.method() at the call site.
Two utilities read and remove this from a function type, which is useful when you write your own bind-style helpers:
function greet(this: { name: string }, punctuation: string) {
return this.name + punctuation;
}
type Ctx = ThisParameterType<typeof greet>; // { name: string }
type Bound = OmitThisParameter<typeof greet>; // (punctuation: string) => string
const hello: Bound = greet.bind({ name: "Ada" });Assertion signatures in practice
You met assertion functions in Unions and narrowing: a return type of asserts condition or asserts value is T tells TypeScript that if the function returns at all, the condition is true. Here is where they earn their keep at work: checking configuration once at startup, and turning "this should never happen" into a loud failure instead of a wrong answer later.
Press Run (⌘ Enter) to see what happens.Compare this with returning string | undefined and checking at every use. The assertion runs once, at the top, and the rest of the function works with plain string. A server that fails at startup with "Missing DATABASE_URL" is far easier to debug than one that crashes on the first request.
Three rules trip people up:
- The function must be declared with an explicit type. Write it as a
functiondeclaration, or annotate the variable. An unannotated arrow fails at the call site with "Assertions require every name in the call target to be declared with an explicit type annotation."
const assertOk = (c: unknown): asserts c => { if (!c) throw new Error(); };
assertOk(maybeName);
// Error: Assertions require every name in the call target to be declared with an explicit type annotation.
const assertOk2: (c: unknown) => asserts c = assert; // annotated: works- They cannot be async.
Promise<asserts x is string>is not allowed, because narrowing has to take effect on the next line, not after anawait. Validate asynchronously, then assert synchronously on the result. - The compiler trusts you. An assertion with a wrong check is worse than none, because it tells TypeScript something false. Keep the body as simple as the signature, or use a schema library's
parse, which is an assertion with a tested body.
Async function types and floating promises
An async function's type is just a function type that returns a promise: (id: string) => Promise<User>, or () => Promise<void> when there is no useful value. The trap is the void rule from earlier. A function type returning void accepts any function, including an async one. So this compiles, and does not do what it looks like:
Press Run (⌘ Enter) to see what happens.forEach expects (value) => void. It calls your async callback, gets a promise back, and throws it away. Nothing waits, so the first log prints 0. The three saves were not cancelled either. They finished in the background while Promise.all ran its own three, which is why the second log prints 6: every record was saved twice. If one of the background saves had failed, the rejection would have had no handler at all. A promise nobody awaits, returns or catches is called a floating promise.
The compiler cannot catch this, because the code is type-correct. The type-aware typescript-eslint rules can, and most teams enable them through the recommendedTypeChecked config:
no-floating-promisesreports a promise-returning call whose result is ignored. If fire-and-forget really is intended, say so withvoid sendAnalytics(event);.no-misused-promisesreports an async function passed where avoid-returning function is expected, like theforEachabove, oronClick={async () => ...}in places where an error would vanish.
When you design an API that takes a callback which might be async and must finish before you move on, put that in the type and await it:
type Hook = () => Promise<void> | void;
async function runHooks(hooks: Hook[]): Promise<void> {
for (const hook of hooks) await hook(); // awaiting a non-promise is harmless
}What does this print?
class Light {
on = false;
toggle() { this.on = !this.on; }
toggleArrow = () => { this.on = !this.on; };
}
const light = new Light();
const results: string[] = [];
for (const fn of [light.toggleArrow, light.toggle]) {
try { fn(); results.push(String(light.on)); }
catch (e) { results.push((e as Error).name); }
}
console.log(results.join(" "));What does this print?
const done: number[] = [];
async function work(n: number) {
await null;
done.push(n);
}
[1, 2, 3].forEach(async (n) => { await work(n); });
console.log(done.length);check(value) fail to compile here, with an error about explicit type annotations?const check = (v: unknown): asserts v is string => {
if (typeof v !== "string") throw new Error("not a string");
};
check(value);What does this print?
const apply = (fn: (n: number) => number, values: number[]) => values.map(fn);
const double = (n: number) => n * 2;
const inc = (n: number) => n + 1;
console.log(apply(double, apply(inc, [1, 2, 3])).join(","));Match the signature to what it says.
Typed pipe
Write pipe, which takes any number of functions and returns one function that runs them left to right, feeding each result into the next.
function pipe<T>(...fns: Array<(value: T) => T>): (value: T) => Tconst slugify = pipe(
(s: string) => s.trim(),
(s: string) => s.toLowerCase(),
(s: string) => s.replaceAll(" ", "-"),
);
slugify(" Hello World ") // "hello-world"With no functions, pipe() returns a function that gives back its input unchanged.
Run a function once
Write once, which wraps a no-argument function so it only ever runs one time. Every later call returns the first result without calling the original again.
function once<R>(fn: () => R): () => Rconst init = once(() => { console.log("connecting"); return 42; });
init(); // logs "connecting", returns 42
init(); // logs nothing, returns 42Careful: the first result might be undefined or 0. It still counts as "already ran".
- return type annotation
- The type after a function's parameter list. Errors in the body are reported inside the function, not at callers.
- optional parameter
- A parameter marked
?(or given a default) that callers may omit. It must come after required ones. - function type
- A type written like
(a: number) => string, used for callbacks and stored functions. - contextual typing
- TypeScript inferring a callback's parameter types from where the callback is used.
- void
- A return type meaning the result should not be used. Typical for handlers and side-effect callbacks.
- overload
- Multiple call signatures for one function, so the return type can depend on the arguments.
- higher-order function
- A function that takes or returns a function, like a retry wrapper. Type it with
A extends unknown[]andRto keep the original signature. - NoInfer<T>
- Marks a parameter so TypeScript checks it against
Tbut does not use it to inferT. Added in TypeScript 5.4. - assertion function
- A function with an
assertsreturn type. If it returns, the condition holds and the value is narrowed on the next line. - floating promise
- A promise that nobody awaits, returns or catches. Its work runs unobserved and its rejection goes unhandled.