Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 96 ยท Functions

Optional, Default and Rest Parameters

Master TypeScript parameter forms - optional vs undefined, defaults that depend on earlier parameters, options objects, rest tuples, labeled elements and spread calls.

Typing Functions introduced optional, default and rest parameters in one pass. This lesson goes deeper, because these three forms hide most of the subtle questions people have about function signatures. Is x?: number the same as x: number | undefined? Can a default value refer to an earlier parameter? How do you type a function whose arguments are "a string, then any number of numbers"? When should several optional parameters become one options object?

You will answer each question with code you can run, and finish with the tuple-based rest parameters that power typed wrappers and event emitters. The ideas build on Function Types and Callbacks and Arrays and Tuples.

Optional is not the same as | undefined

A parameter marked ? may be omitted by the caller. A parameter typed T | undefined may be passed as undefined, but it must still be passed. The difference only shows in the call:

TypeScript Optional versus a required undefined

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is x none, x none, x none, then y none z 3. Use ? when callers may leave the argument out, and T | undefined when you want to force them to say "I know there is no value" explicitly. The second form is rare, but it is useful in functions where forgetting an argument would be a bug, such as setTimer(delay: number | undefined).

Inside the function, an optional parameter has type T | undefined, so you must handle that case before using it as T. Most of the time you do that with ?? (nullish coalescing) or a default value, which is the next topic.

Default values

A default value gives a parameter a value when the caller passes undefined or nothing at all. It also gives the parameter a type, so you rarely need to write one:

TypeScript
function pad(text: string, width = 8, fill = ' '): string {
  return text.padStart(width, fill);
}
// width: number, fill: string, both optional for callers

Three details matter in practice.

Defaults run at call time, left to right. The default expression is evaluated every time it is needed, not once when the function is defined. And a default can use parameters that come before it:

TypeScript Defaults are evaluated at each call and can use earlier parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each call to createItem gets a new id (1, 2, 3) and a new tags array, so ['new'] is printed three times. Compare that with a classic JavaScript bug: a shared default array defined outside the function would grow with each call. A default expression inside the parameter list is safe because it re-runs.

Using a later parameter in an earlier default is an error. TypeScript reports TS2373, "Parameter 'a' cannot reference identifier 'b' declared after it". The width(0) line also shows that only undefined triggers a default: 0, '', false and null are real values and are kept. (With strictNullChecks, passing null to w: number is a type error anyway.)

A default can be placed before a required parameter, but then callers must pass undefined to reach it. That is legal and occasionally handy, but usually a sign that the order should change:

TypeScript
function format(prefix = '>', message: string): string {
  return `${prefix} ${message}`;
}
format(undefined, 'hello');   // the only way to use the default prefix

The type shown to callers is optional. Hovering over createItem in an editor shows (name: string, slug?: string, id?: number, tags?: string[]). The ? there is not something you wrote; it is how TypeScript presents a parameter with a default. Inside the body, though, the type is the plain string, never string | undefined.

The order rules

Putting the rules in one place:

Written as Allowed? Notes
(a: string, b?: number) Yes optional after required
(a?: string, b: number) No, TS1016 required parameter cannot follow optional
(a: string, b = 1, c: number) Yes defaults may come before required ones; callers pass undefined
(a?: string = 'x') No, TS1015 a default already makes it optional
(...rest: number[], last: number) No, TS1014 the rest parameter must be last

The rest parameter must always be the final one, and there can be only one.

When many optionals become an options object

Parameters are positional. A function with four optional parameters forces callers to write render(text, undefined, undefined, true) to set the fourth one. That is unreadable. When you have more than two optional values, switch to a single options object with a type and defaults through destructuring:

TypeScript An options object with destructured defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints 12.50 USD, 12.50 EUR and +7 USD. Notice the final = {}: it makes the whole second argument optional, so formatMoney(12.5) works. Without it, you would have to pass at least {}. Callers name what they set, order does not matter, and adding a new option later does not break existing calls. The cost is one more object per call, which is negligible outside the hottest loops.

A good rule: up to two optional parameters stay positional; beyond that, use an options object. Keep the required, essential values (here amount) as normal parameters.

Rest parameters

A rest parameter collects the remaining arguments into an array. You saw ...numbers: number[] already. Two more forms are worth knowing.

Readonly arrays. If the function never changes its arguments and you want callers to be able to spread a readonly array into it, type the rest parameter as readonly T[]:

TypeScript
function max(...values: readonly number[]): number {
  return Math.max(...values);
}
const frozen: readonly number[] = [3, 9, 4];
max(...frozen);   // fine

Tuple types. A rest parameter can be a tuple, which gives you fixed positions, optional positions and a variable tail, all while keeping the call syntax natural. The editor shows the parameters like any other signature:

TypeScript Rest parameters typed as tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is scores: n=3, total=252, empty: n=0, total=0, http://example.org:80 and https://example.org:8443. The labels (label, values, host, port) do not change how the type is checked; they only improve the parameter names that editors show in signature help.

Typing a wrapper with Parameters<T>

Tuple rest parameters are the key to forwarding arguments without retyping them. The Parameters<F> utility extracts the parameter list of a function type as a tuple, and ReturnType<F> its result. Combined with a generic and a rest parameter, they let you wrap any function:

TypeScript A typed wrapper that forwards its arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

loggedArea has exactly the signature of area, including the optional second parameter: (width: number, height?: number) => number. The output shows calling area with [ 3, 4 ], 12, calling area with [ 5 ] and 25. This pattern is behind many typed helpers: debounce, memoize, retry and event emitters. For more on Parameters and friends, see Utility Types.

flowchart LR
    S["area: (width: number, height?: number) => number"] --> P["Parameters of area<br/>= [width: number, height?: number]"]
    P --> W["wrapper takes ...args of that tuple"]
    W --> C["call fn with ...args"]
    S --> R["ReturnType of area = number"]
    R --> W

How a wrapper reuses the parameter list and result type of the function it wraps.

Spreading into a call

Spreading an array into a call has one more rule. If the receiving function has rest parameters, any array works. If it has fixed parameters, the argument must be a tuple of known length, because the compiler has to count:

TypeScript
function distance(x: number, y: number): number {
  return Math.hypot(x, y);
}

const pair = [3, 4];                  // number[]
// distance(...pair);                 // error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.

const pairTuple: [number, number] = [3, 4];
distance(...pairTuple);               // fine

const pairConst = [3, 4] as const;    // readonly [3, 4]
distance(...pairConst);               // fine

The as const trick is the quickest way to get a tuple from a literal. See Literal Types and as const.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given function f(a: string, b: number | undefined), which call compiles?

    A parameter typed number | undefined is still required. It can receive undefined, but it cannot be omitted. Only a ? makes it omittable.
  2. 2. What does a default value give the parameter inside the function body?

    Inside the body the type is the plain declared or inferred type. Callers see the parameter as optional.
  3. 3. Which value triggers the default in function w(n: number = 100)?

    Only undefined (or omitting the argument) triggers a default. Falsy values like 0 are real values and are kept.
  4. 4. What is wrong with function f(...rest: number[], last: string)?

    Everything after the rest parameter would be unreachable, so TypeScript requires the rest parameter to come last (TS1014).
  5. 5. Why does distance(...pair) fail when pair is a number[] and distance has two fixed parameters?

    For fixed parameters the compiler needs to know the number of elements, so the argument must be a tuple (or as const) rather than an ordinary array.

Summary

  • b?: T lets callers omit the argument; b: T | undefined makes them pass something, even if that something is undefined.
  • Default values are evaluated on every call, left to right, can use earlier parameters, and only react to undefined. Inside the body the type has no undefined.
  • A required parameter cannot follow an optional one, ? and a default cannot be combined, and the rest parameter must be last.
  • With more than two optional values, take one options object and destructure it with defaults, ending with = {} so the whole argument is optional.
  • Rest parameters can be arrays, readonly arrays or tuples with labels, optional elements and a variable tail.
  • Parameters<F> and ReturnType<F> with a rest parameter let you write wrappers that keep the original signature.
  • Spreading into fixed parameters needs a tuple or an as const array.

Next: Narrowing