Skip to content

Lesson 38 of 50TypeScript

Typing Functions

Type parameters, returns, callbacks, overloads, higher-order wrappers, this, assertion functions and async callbacks without floating promises.

22 min read0/7 questions

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'.
}
Anatomy of a typed function
function formatPricedeclaration<T>type parameters (optional, see Generics)(cents: number, currency?: string)parameters with types: stringreturn type{ body }must return a string on every pathroot

Each parameter gets a type. ? marks one as optional.

1/3

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.

TypeScript
function greet(name: string, greeting?: string): string { return `${greeting ?? "Hello"}, ${name}!`;} function repeat(text: string, times = 2): string { return text.repeat(times); // times: number, inferred from the default} console.log(greet("Ada"));console.log(greet("Sam", "Welcome"));console.log(repeat("ab"));console.log(repeat("ab", 3));
Output
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 });
Quick check
Does this compile?
function log(level?: string, message: string) {}
Need a nudge? A hint rules out a wrong answer.

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 number

That 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.

TypeScript
type Validator = (value: string) => string | null; // null means "valid" const rules: Validator[] = [ (v) => (v.length === 0 ? "Required" : null), (v) => (v.includes("@") ? null : "Must contain @"),]; function validate(value: string, validators: Validator[]): string[] { return validators.map((rule) => rule(value)).filter((msg) => msg !== null);} console.log(validate("", rules));console.log(validate("ada@example.com", rules));
Output
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: OK

undefined as a return type is stricter: the function must actually return undefined. Use void for "nothing useful", and T | undefined for "maybe a value".

Quick check
Does this compile?
type Handler = () => void;
const h: Handler = () => 42;
Need a nudge? A hint rules out a wrong answer.

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:

TypeScript
function withRetry<A extends unknown[], R>( fn: (...args: A) => Promise<R>, attempts = 3,): (...args: A) => Promise<R> { return async (...args) => { let lastError: unknown; for (let i = 1; i <= attempts; i++) { try { return await fn(...args); } catch (e) { lastError = e; console.log(`attempt ${i} failed: ${(e as Error).message}`); } } throw lastError; };} let calls = 0;async function loadInvoice(id: string, includeLines: boolean) { calls++; if (calls < 3) throw new Error("503 from billing"); return { id, lines: includeLines ? 4 : 0 };} const loadInvoiceSafely = withRetry(loadInvoice);// (id: string, includeLines: boolean) => Promise<{ id: string; lines: number }> const invoice = await loadInvoiceSafely("inv_42", true);console.log(invoice.id, invoice.lines);// loadInvoiceSafely("inv_42");// Error: Expected 2 arguments, but got 1.
Output
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.

TypeScript
class Counter { count = 0; increment() { this.count++; } incrementArrow = () => { this.count++; };} const counter = new Counter();const handlers = [counter.increment, counter.incrementArrow]; // detached from counter for (const handler of handlers) { try { handler(); console.log("worked, count is", counter.count); } catch (e) { console.log("failed with", (e as Error).name); }}
Output
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.

TypeScript
function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(`Assertion failed: ${message}`);} function assertDefined<T>(value: T, name: string): asserts value is NonNullable<T> { if (value === undefined || value === null) throw new Error(`Missing ${name}`);} function loadConfig(env: Record<string, string | undefined>) { const url = env.DATABASE_URL; // string | undefined assertDefined(url, "DATABASE_URL"); const port = Number(env.PORT ?? "5432"); assert(Number.isInteger(port) && port > 0, "PORT must be a positive integer"); return { url, port }; // url: string from here on} const config = loadConfig({ DATABASE_URL: "postgres://db/app", PORT: "6543" });console.log(config.url, config.port); for (const env of [{ PORT: "5432" }, { DATABASE_URL: "postgres://db/app", PORT: "abc" }]) { try { loadConfig(env); } catch (e) { console.log((e as Error).message); }}
Output
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 function declaration, 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 an await. 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:

TypeScript
const saved: string[] = []; async function save(id: string): Promise<void> { await new Promise((resolve) => setTimeout(resolve, 10)); saved.push(id);} const ids = ["a", "b", "c"]; ids.forEach(async (id) => { await save(id); // forEach does not wait for this});console.log("after forEach:", saved.length); await Promise.all(ids.map((id) => save(id)));console.log("after Promise.all:", saved.length);
Output
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-promises reports a promise-returning call whose result is ignored. If fire-and-forget really is intended, say so with void sendAnalytics(event);.
  • no-misused-promises reports an async function passed where a void-returning function is expected, like the forEach above, or onClick={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
}
Predict the outputTypeScript

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(" "));
Need a nudge? Hints walk you through it.
Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.
Quick check
Why does calling 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);
Need a nudge? A hint rules out a wrong answer.
Predict the outputTypeScript

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(","));
Need a nudge? Hints walk you through it.
Match the pairs0/4 matched

Match the signature to what it says.

Choose an item, then its match on the other side.
ChallengeMedium

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) => T
const 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.

TypeScript
function pipe<T>(...fns: Array<(value: T) => T>): (value: T) => T { return (value: T) => value;}
ChallengeEasy

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): () => R
const init = once(() => { console.log("connecting"); return 42; });
init(); // logs "connecting", returns 42
init(); // logs nothing, returns 42

Careful: the first result might be undefined or 0. It still counts as "already ran".

TypeScript
function once<R>(fn: () => R): () => R { return fn;}
Key terms
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[] and R to keep the original signature.
NoInfer<T>
Marks a parameter so TypeScript checks it against T but does not use it to infer T. Added in TypeScript 5.4.
assertion function
A function with an asserts return 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.