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.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Syntax
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 28, 2026
Related tutorials
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#
function greet(name: string, title?: string, greeting = 'Hello') { }
function sum(...nums: number[]): number { }
Code example: Optional, default, rest and options#
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'
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#
- last?: string means callers can skip it; TypeScript forces a check before using it.
- greeting has a default, so inside the function it is always a string.
- ...nums: number[] collects any number of numeric arguments.
- PaginateOptions makes every option optional; destructuring gives each a default.
- = {} lets callers omit the options object entirely.
- 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#
function f(a?: string, b: string) is an error. Required parameters must come first.
An optional parameter must be checked (if, ??, ?.) before use.
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?
Show solution
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#
Inside function f(x?: number), what is the type of x?
Want more? Practise all TypeScript MCQs · TypeScript interview questions
My notes#
Saved in this browser.