Menu

Function Types and Callbacks

Lesson 3: Function Types and Callbacks

How do you describe a function as a type?

Syntax Meaning
(a: number) => string Takes a number, returns a string
type Handler = (event: OrderEvent) => void Named function type
{ (a: number): string } Call signature in object form
(...args: string[]) => void Any number of string arguments

Example

type Product = { name: string; price: number; category: string };

type ProductFilter = (product: Product) => boolean;

const isAffordable: ProductFilter = (p) => p.price <= 10000;
const isDairy: ProductFilter = (p) => p.category === 'dairy';

function filterProducts(items: Product[], ...filters: ProductFilter[]): Product[] {
  return items.filter((item) => filters.every((f) => f(item)));
}

// Higher-order function: returns a function
function priceAbove(min: number): ProductFilter {
  return (p) => p.price > min;
}

filterProducts(catalogue, isDairy, priceAbove(5000));

// Callback type for events
type OrderListener = (orderId: string, status: string) => void;

function onStatusChange(listener: OrderListener) {
  listener('QC-1042', 'shipped');
}

onStatusChange((id, status) => console.log(`${id} is now ${status}`));

How it works

  • In const isAffordable: ProductFilter = (p) => ..., the parameter p is typed from context, so it needs no annotation.
  • Named function types make callback-heavy code readable and reusable.
  • **void** return in a function type means "the return value is ignored". A callback that returns something can still be passed, which is why [1, 2].forEach(n => list.push(n)) is allowed even though push returns a number.

Common mistakes

Mistake Effect Fix
Typing callbacks as Function No checking of arguments or return Write the exact signature
Annotating every callback parameter Noisy; may conflict with context Let contextual typing infer them
Making callback parameters optional ((id?: string) => void) Callers must handle undefined needlessly Callbacks may ignore parameters; keep them required

Key takeaways

  • Function types describe parameters and return values: (x: T) => R.
  • Callbacks are typed from context, so annotate the function type once.

Try it: Create a PriceRule function type and three rules (festival discount, bulk discount, prime discount). Apply them in sequence to a cart total.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details