- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
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.
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.
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
ageparameter is initialized with a default value of30. - When we call
greet("John"), we only provide one argument. TypeScript sees thatageis missing and fills it in with30.
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.
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
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
categorydefaults to"General"if we passundefined. - The
...entriesrest 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.