Callbacks and function signatures

7.0.2

Write types for functions you pass as values and be clear about which arguments callers must provide.

On this page

Type a callback

Use a function type to describe the parameters and return value of a callback. Callers can then use the same function contract with different implementations.

type PriceRule = (price: number) => number;

function applyRule(price: number, rule: PriceRule): number {
  return rule(price);
}

const salePrice = applyRule(5, amount => amount * 0.8);

Choose optional or default parameters

A parameter marked with ? may be omitted, so handle undefined in the body. A default is used when the caller omits the argument or passes undefined. Use an overload only where a union parameter cannot express the relationship clearly.

function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}!` : `Hello, ${name}!`;
}

function formatPrice(amount: number, currency = "USD"): string {
  return `${amount} ${currency}`;
}

console.log(greet("Taylor"));             // Hello, Taylor!
console.log(greet("Taylor", "Dr."));      // Hello, Dr. Taylor!
console.log(formatPrice(12));            // 12 USD
console.log(formatPrice(12, "EUR"));     // 12 EUR

Official references