Skip to Content
FunctionsDefault Parameters

Default Parameters in TypeScript Functions

Default parameters allow you to provide default values for function parameters. If the caller doesn’t provide a value, or explicitly passes undefined, the default value is used.

Basic Syntax

In TypeScript, you can specify a default value directly in the parameter list using the assignment operator =.

function functionName(param1: type = defaultValue): returnType { // function body }

Simple Example

function greet(name: string = "Guest"): void { console.log(`Hello, ${name}!`); } greet("Alice"); // Uses "Alice" greet(); // Uses default "Guest" greet(undefined); // Also uses default "Guest"

Output:

Hello, Alice! Hello, Guest! Hello, Guest!

How It Works

When you call greet() without arguments:

  • The function uses the default value "Guest"

When you call greet("Alice"):

  • The provided value "Alice" overrides the default

Multiple Default Parameters

You can have multiple parameters with defaults. Also, notice that TypeScript can often infer the parameter types if a default value is provided (e.g., age = 0 implies age is a number):

function displayInfo(name: string = "Unknown", age: number = 0, city: string = "Not specified"): void { console.log(`Name: ${name}`); console.log(`Age: ${age}`); console.log(`City: ${city}`); console.log("---"); } displayInfo("Alice", 25, "New York"); displayInfo("Bob", 30); displayInfo("Charlie"); displayInfo();

Output:

Name: Alice Age: 25 City: New York --- Name: Bob Age: 30 City: Not specified --- Name: Charlie Age: 0 City: Not specified --- Name: Unknown Age: 0 City: Not specified ---

Parameter Order

Unlike some other languages, TypeScript allows default parameters to appear anywhere in the declaration. However, if a default parameter precedes a required parameter, users must explicitly pass undefined to get the default initialized value. It is generally a best practice to put default parameters at the end of the parameter list.

✅ Good Practice (Defaults at the end)

function buildName(firstName: string, lastName: string = "Smith") { return `${firstName} ${lastName}`; } let result1 = buildName("Bob"); // "Bob Smith" let result2 = buildName("Bob", "Adams"); // "Bob Adams"

⚠️ Allowed but Awkward (Defaults before required)

function buildNameReverse(firstName: string = "Will", lastName: string) { return `${firstName} ${lastName}`; } // let result3 = buildNameReverse("Adams"); // Error: Expected 2 arguments, but got 1. let result4 = buildNameReverse(undefined, "Adams"); // "Will Adams"

Practical Example: Power Function

// Calculate power with default exponent of 2 (square) function power(base: number, exponent: number = 2): number { return Math.pow(base, exponent); } console.log(`5^3 = ${power(5, 3)}`); // 125 console.log(`4^2 = ${power(4)}`); // 16 (default exponent) console.log(`7^2 = ${power(7)}`); // 49 (default exponent)

Output:

5^3 = 125 4^2 = 16 7^2 = 49

Rectangle Area with Default Square

// If height not provided, assumes it's a square function calculateArea(width: number, height: number = width): number { return width * height; } console.log(`Rectangle 5x3: ${calculateArea(5, 3)}`); console.log(`Square 4x4: ${calculateArea(4)}`);

Output:

Rectangle 5x3: 15 Square 4x4: 16

Printing with Default Separator

function printWithSeparator(text: string, separator: string = '-', count: number = 20): void { const divider = separator.repeat(count); console.log(divider); console.log(text); console.log(divider); } printWithSeparator("Title 1"); printWithSeparator("Title 2", '*'); printWithSeparator("Title 3", '=', 30);

Output:

-------------------- Title 1 -------------------- ******************** Title 2 ******************** ============================== Title 3 ==============================

Interest Calculator

// Calculate simple interest with default rate of 5% function calculateInterest(principal: number, time: number, rate: number = 5.0): number { return (principal * time * rate) / 100; } console.log(`Interest on $1000 for 2 years at 5%: $${calculateInterest(1000, 2)}`); console.log(`Interest on $1000 for 2 years at 7%: $${calculateInterest(1000, 2, 7.0)}`);

Output:

Interest on $1000 for 2 years at 5%: $100 Interest on $1000 for 2 years at 7%: $140

Logger Function

type LogLevel = "INFO" | "DEBUG" | "WARN" | "ERROR"; function log(message: string, level: LogLevel = "INFO"): void { console.log(`[${level}] ${message}`); } log("Application started"); log("User logged in", "DEBUG"); log("Database connection failed", "ERROR"); log("Processing data");

Output:

[INFO] Application started [DEBUG] User logged in [ERROR] Database connection failed [INFO] Processing data

Optional vs Default Parameters

Both optional (?) and default (=) parameters allow the caller to omit an argument, but they behave slightly differently regarding assigned types.

Optional Parameters

If you use ?, the parameter’s type implicitly includes undefined.

function sayHi(name?: string) { // inside the function, name is of type `string | undefined` const finalName = name || "Guest"; console.log(`Hi ${finalName}`); }

Default Parameters

If you use =, the parameter gets a guaranteed type, because it will be filled with the default value if omitted.

function sayHiDefault(name: string = "Guest") { // inside the function, name is guaranteed to be a `string` console.log(`Hi ${name.toUpperCase()}`); }

Note: You cannot combine both like name?: string = "Guest".

Best Practices

  1. Use sensible defaults: Choose defaults that cover the most common use case.
  2. Put required parameters first: This makes the function signature clearer and avoids having to pass undefined manually.
  3. Don’t overuse: Too many defaults can make code hard to understand. Sometimes a configuration object (interface Options { ... }) is better.
  4. Leverage type inference: If your default value is a literal like 0 or "", you can optionally omit the type annotation completely (function foo(age = 0)).

Next Steps

  • Explore REST parameters (...args: type[]) for an infinite number of arguments.
  • Learn about Function Overloading to provide different signatures for the same function.

Default parameters make your functions more flexible and easier to use while keeping TypeScript’s strict type checking!

Last updated on