TypeScript · Functions

Optional and Default Parameters

Not every argument is always needed. TypeScript lets you mark parameters as optional or give them defaults — and checks that you handle the missing case.

Intermediate 5 min Lesson 13 of 29Examples target TypeScript 5.x with "strict": true.
0/29 in TypeScript
On this page · 5 min · Intermediate

Learning objectives#

  • Mark parameters as optional with ?
  • Give parameters default values
  • Type rest parameters
  • Type a destructured options object

Explanation#

name?: string makes a parameter optional. Inside the function its type is string | undefined, so you must handle undefined.

A default value (greeting = "Hello") also makes the parameter optional, and its type is inferred from the default — no undefined to handle.

Optional and defaulted parameters should come after required ones.

Rest parameters are typed as arrays: function sum(...nums: number[]).

For many options, use one typed object: function connect({ host = "localhost", port = 5432 }: ConnectOptions = {}).

Syntax#

TypeScript Illustrative
function greet(name: string, title?: string, greeting = 'Hello') { }
function sum(...nums: number[]): number { }

Code example: Optional, default, rest and options#

TypeScriptOptional, default, rest and options Illustrative
function fullName(first: string, last?: string): string {
  // return first + ' ' + last.toUpperCase();   // ✗ 'last' is possibly 'undefined'
  return last ? `${first} ${last}` : first;
}


function greet(name: string, greeting = 'Namaste'): string {
  return `${greeting}, ${name}!`;          // greeting is string, never undefined
}


function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}


interface PaginateOptions {
  page?: number;
  pageSize?: number;
  sort?: 'asc' | 'desc';
}
function paginate<T>(items: T[], { page = 1, pageSize = 10, sort = 'asc' }: PaginateOptions = {}): T[] {
  const sorted = sort === 'asc' ? items : [...items].reverse();
  return sorted.slice((page - 1) * pageSize, page * pageSize);
}


fullName('Asha');                       // 'Asha'
greet('Ravi');                          // 'Namaste, Ravi!'
sum(1, 2, 3);                           // 6
paginate([1, 2, 3, 4, 5], { pageSize: 2, page: 2 });   // [ 3, 4 ]
paginate([1, 2], { sort: 'random' });   // ✗ Type '"random"' is not assignable to type '"asc" | "desc" | undefined'
Expected output
fullName('Asha') → 'Asha', greet('Ravi') → 'Namaste, Ravi!', sum → 6, paginate → [ 3, 4 ]. The invalid sort option is rejected.

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. last?: string means callers can skip it; TypeScript forces a check before using it.
  2. greeting has a default, so inside the function it is always a string.
  3. ...nums: number[] collects any number of numeric arguments.
  4. PaginateOptions makes every option optional; destructuring gives each a default.
  5. = {} lets callers omit the options object entirely.
  6. A wrong literal value inside the options is still caught.

Real-world use case#

API helpers like fetchProducts({ category, page = 1 }) and UI utilities like formatDate(date, locale = "en-IN") rely on optional and default parameters.

Common mistakes#

Optional before required

function f(a?: string, b: string) is an error. Required parameters must come first.

Using a value that may be undefined

An optional parameter must be checked (if, ??, ?.) before use.

Both ? and a default

function f(x?: number = 5) is not allowed — a default already makes it optional.

Best practices#

  • Prefer defaults over ? when a sensible default exists
  • Use an options object once you have more than 2 optional parameters
  • Always add = {} to an optional destructured options object
  • Use ?? to supply defaults inside the function when needed

Remember this#

? = may be missing (handle undefined). = value = may be missing (default fills it).

Required first, optional last.

Many options? One typed object with defaults.

Practice exercise#

Your task: Write formatDate(date: Date, options?) where options has optional locale (default "en-IN") and withTime (default false).

Need a hint?
Destructure the options with defaults and = {}.
Show solution
TypeScript Illustrative
interface DateOptions { locale?: string; withTime?: boolean }


function formatDate(date: Date, { locale = 'en-IN', withTime = false }: DateOptions = {}): string {
  return withTime ? date.toLocaleString(locale) : date.toLocaleDateString(locale);
}
formatDate(new Date(), { withTime: true });

Mini quiz#

Optional and Default Parameters quizMultiple choice Question 1 of 3

Inside function f(x?: number), what is the type of x?

Score so far: 0/0

Want more? Practise all TypeScript MCQs · TypeScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.