TypeScript Default Parameters

In TypeScript, default parameters allow you to assign a fallback value to a function parameter. If the caller of the function doesn't provide an argument for that parameter—or explicitly passes undefined—the default value takes over. This makes your functions more resilient and helps you avoid writing repetitive "if-check" logic at the start of your functions to handle missing data.

Developer Tip: Before default parameters were standard in ES6 (and TypeScript), developers had to use the logical OR operator (e.g., param = param || 'default'). Using TypeScript's built-in syntax is much safer because it specifically looks for undefined rather than any "falsy" value like 0 or an empty string.

 

Syntax for Default Parameters

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

The syntax is straightforward: you place an equals sign (=) and the value right after the type annotation. TypeScript is also smart enough to infer the type of the parameter from the default value if you choose to omit the explicit type.

Best Practice: If you provide a default value, TypeScript can usually infer the type for you. For example, function setVolume(level = 10) automatically treats level as a number. Only add the explicit type if it makes the code easier for your team to read or if the type is complex.

Example of Default Parameters

Let’s look at a basic greeting function. In many applications, you might want to provide a standard value if user data is incomplete.

function greet(name: string, age: number = 30): string {
  return `Hello ${name}, age ${age}`;
}

console.log(greet("John"));        // Output: Hello John, age 30
console.log(greet("Alice", 25));   // Output: Hello Alice, age 25

In this example:

  • The age parameter is initialized with a default value of 30.
  • When we call greet("John"), we only provide one argument. TypeScript sees that age is missing and fills it in with 30.
Watch Out: Default parameters only trigger for undefined. If you pass null to a function with a default parameter, TypeScript will treat null as a valid value and will not use the default value.

Default Parameters with Multiple Parameters

You can assign default values to as many parameters as you like. This is common when building configuration functions or UI components where most settings stay the same but need to be customizable.

function createUser(name: string, age: number = 18, city: string = "New York"): string {
  return `Name: ${name}, Age: ${age}, City: ${city}`;
}

console.log(createUser("John"));                 // Output: Name: John, Age: 18, City: New York
console.log(createUser("Alice", 25));            // Output: Name: Alice, Age: 25, City: New York
console.log(createUser("Bob", 30, "Los Angeles")); // Output: Name: Bob, Age: 30, City: Los Angeles

By defining defaults for age and city, we've essentially created three different ways to call this function without having to write three separate function overloads.

Common Mistake: Placing default parameters before required parameters. While TypeScript technically allows function fn(a = 1, b: number), you would have to explicitly pass undefined as the first argument to use the default. It’s much better to put your required parameters first.

Default Parameters with Optional Parameters

It is important to understand the difference between an optional parameter (using ?) and a default parameter. An optional parameter will be undefined if not provided, while a default parameter will always have a value.

function displayMessage(message: string, prefix: string = "Info"): string {
  return `${prefix}: ${message}`;
}

console.log(displayMessage("Server is running"));        // Output: Info: Server is running
console.log(displayMessage("Server is running", "Alert")); // Output: Alert: Server is running
Watch Out: You cannot mark a parameter as both optional and provide a default value. For example, prefix?: string = "Info" will result in a TypeScript error. The default value already makes the parameter optional by nature.

Combining Default Parameters with Rest Parameters

Rest parameters (...args) allow a function to accept an indefinite number of arguments as an array. You can use default parameters alongside them to set a base state for your function.

function logEntries(category: string = "General", ...entries: string[]): void {
  console.log(`Category: ${category}`);
  entries.forEach(entry => console.log(` - ${entry}`));
}

logEntries(undefined, "User logged in", "Page refreshed"); 
// Output: 
// Category: General
// - User logged in
// - Page refreshed

In this real-world scenario:

  • The category defaults to "General" if we pass undefined.
  • The ...entries rest parameter captures all subsequent strings into an array, allowing for flexible logging.

 

Summary

Default parameters in TypeScript are a powerful tool for writing cleaner, more readable code. They allow you to define a sensible fallback for data, reducing the need for manual null-checks or complex function signatures. By following the pattern of placing default parameters at the end of your parameter list, you ensure your functions are easy for other developers to use and maintain.

Best Practice: Use default parameters for configuration objects or settings. It provides a clear "contract" for what the function expects while making the most common use cases require the least amount of code.