liveBook · Manning

Optional function argument

As explained in Essential TypeScript 5, Third Edition

An optional parameter is a function parameter that may be omitted by the caller and is denoted with a question mark in TypeScript.

TypeScript requires an argument for every function parameter by default. Add `?` after a parameter name when callers may omit that argument. Optional parameters must come after required parameters. section 8.2.2

Call a function with or without a discount

In `src/index.ts`: ```ts function calculateTax(amount, discount?) { return (amount * 1.2) - (discount || 0); } console.log(calculateTax(100, 0)); // 120 console.log(calculateTax(100)); // 120 ``` The second call supplies `undefined` for `discount`. The function uses `|| 0` so it can still calculate a result. Making `discount` optional does not permit an extra third argument. section 8.2.2

A default parameter offers another way to allow omission: `discount = 0` assigns the fallback in the parameter declaration instead of the calculation. A rest parameter serves a different purpose: accepting additional arguments. section 8.2.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains declaration syntax, required-parameter ordering, omitted values, and the need for a fallback; does not explore compiler internals.
Examples
Uses a tax calculation called with one or two arguments, plus a rejected call with three.
What it assumes
Assumes familiarity with JavaScript function calls while introducing TypeScript’s `?` notation for parameters.
What you can do after
Apply it in TypeScript functions to permit omitted arguments while handling the resulting `undefined` value.
How it connects
Contrasts optional parameters with default parameters for omitted arguments and rest parameters for additional arguments.

Also explained in

Compare how 4 books explain optional function argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.