Menu

Optional, Default, and Rest Parameters

Lesson 2: Optional, Default, and Rest Parameters

What kinds of parameters are there?

Kind Syntax Type inside the function Example call
Required qty: number number f(2)
Optional note?: string `string undefined`
Default slot = 'morning' Inferred from the default f() uses 'morning'
Rest ...ids: string[] string[] f('a', 'b', 'c')

Optional and default parameters must come after required ones.

Example

function scheduleDelivery(
  orderId: string,
  slot: 'morning' | 'afternoon' | 'evening' = 'morning',
  note?: string,
): string {
  return `Order ${orderId} → ${slot}${note ? ` (${note})` : ''}`;
}

scheduleDelivery('QC-1042');                     // morning
scheduleDelivery('QC-1042', 'evening', 'Ring bell');

function totalOf(...amounts: number[]): number {
  return amounts.reduce((sum, a) => sum + a, 0);
}
totalOf(6400, 64500, 6000); // 76900

// Destructured options object with defaults
function searchProducts({
  query,
  category = 'all',
  limit = 20,
}: {
  query: string;
  category?: string;
  limit?: number;
}) {
  return `Searching "${query}" in ${category}, top ${limit}`;
}
searchProducts({ query: 'rice' });

How it works

  • A default value makes the parameter optional for callers, and its type is inferred from the default.
  • Rest parameters collect any number of arguments into an array.
  • For functions with more than three parameters, an options object is clearer: callers name each argument, and order no longer matters.

Common mistakes

Mistake Effect Fix
Optional parameter before a required one Error Put required parameters first, or use an options object
Using note without checking it Possibly undefined error Check it, or give it a default
Long lists of positional booleans (f(true, false, true)) Unreadable calls Use an options object

Key takeaways

  • ? makes a parameter optional; a default value also makes it optional and fills it in.
  • Rest parameters type variable-length arguments as an array.
  • Prefer options objects for functions with many settings.

Try it: Write createOrder(customerId: string, ...items: CartItem[]) that returns an order with a computed total.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details