TYPESCRIPT
TypeScript Default Parameter: Syntax, Usage, and Examples
A TypeScript default parameter allows you to specify a fallback value for a function parameter when the caller does not provide an argument. This feature simplifies function calls, reduces the need for extra conditionals, and improves code readability.
How to Use Default Parameters in TypeScript
Define a default parameter by assigning a value directly in the function definition. When an argument is missing, TypeScript automatically assigns the default value.
function greet(name: string = "Guest"): string {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet("Alice")); // Output: Hello, Alice!
Default Values in Function Parameters
A function can have multiple parameters with default values, but they must appear after required parameters.
function orderItem(item: string, quantity: number = 1): string {
return `You ordered ${quantity} ${item}(s).`;
}
console.log(orderItem("apple")); // Output: You ordered 1 apple(s).
console.log(orderItem("banana", 3)); // Output: You ordered 3 banana(s).
Default Parameters in Arrow Functions
Default parameters work the same way in arrow functions.
const multiply = (a: number, b: number = 2): number => a * b;
console.log(multiply(5)); // Output: 10
console.log(multiply(5, 3)); // Output: 15
When to Use Default Parameters in TypeScript
Providing Sensible Defaults
Default parameters make functions more convenient to use by setting meaningful default values.
function connectToServer(url: string = "https://api.example.com"): void {
console.log(`Connecting to ${url}...`);
}
connectToServer(); // Output: Connecting to https://api.example.com...
connectToServer("https://custom-api.com"); // Output: Connecting to https://custom-api.com...
Reducing Conditional Checks
Instead of manually checking if a parameter exists and assigning a fallback, default parameters simplify the logic.
function calculateDiscount(price: number, discount: number = 10): number {
return price - (price * discount) / 100;
}
console.log(calculateDiscount(100)); // Output: 90
console.log(calculateDiscount(100, 20)); // Output: 80
Improving Code Readability
Using default parameters makes functions more readable by clearly specifying what happens when an argument is missing.
function sendMessage(message: string, sender: string = "System"): void {
console.log(`${sender}: ${message}`);
}
sendMessage("Welcome!"); // Output: System: Welcome!
sendMessage("Hello!", "Alice"); // Output: Alice: Hello!
Examples of Default Parameters in TypeScript
Using Default Parameters in Class Methods
Default parameters can be used inside class methods, making class-based APIs easier to work with.
class Logger {
log(message: string, level: string = "INFO"): void {
console.log(`[${level}] ${message}`);
}
}
const logger = new Logger();
logger.log("System started"); // Output: [INFO] System started
logger.log("Critical error", "ERROR"); // Output: [ERROR] Critical error
Combining Default Parameters with Rest Parameters
You can use default parameters with rest parameters to make flexible functions.
function logMessages(prefix: string = "Log:", ...messages: string[]): void {
messages.forEach((msg) => console.log(`${prefix} ${msg}`));
}
logMessages("INFO", "User logged in", "Data loaded");
// Output: INFO User logged in
// Output: INFO Data loaded
logMessages(undefined, "Server restarted");
// Output: Log: Server restarted
Default Parameters in Asynchronous Functions
When working with async functions, default parameters help handle optional values gracefully.
async function fetchData(endpoint: string = "/default-endpoint"): Promise<void> {
const response = await fetch(`https://api.example.com${endpoint}`);
console.log(await response.json());
}
fetchData(); // Fetches data from /default-endpoint
fetchData("/custom-endpoint"); // Fetches data from /custom-endpoint
Learn More About Default Parameters in TypeScript
Default vs. Optional Parameters
Although they seem similar, default parameters and optional parameters behave differently.
- Default parameters provide a fallback value.
- Optional parameters, denoted by
?
, areundefined
when omitted.
function greetUser(name?: string): string {
return `Hello, ${name || "Guest"}!`;
}
console.log(greetUser()); // Output: Hello, Guest!
console.log(greetUser("Alice")); // Output: Hello, Alice!
Default Parameters with TypeScript Function Overloading
You can use function overloading with default parameters for flexible function signatures.
function getUserInfo(id: number): string;
function getUserInfo(name: string): string;
function getUserInfo(idOrName: number | string = "Guest"): string {
return typeof idOrName === "number" ? `User ID: ${idOrName}` : `User: ${idOrName}`;
}
console.log(getUserInfo(42)); // Output: User ID: 42
console.log(getUserInfo("Alice")); // Output: User: Alice
console.log(getUserInfo()); // Output: User: Guest
Default Parameter Limitations
Default parameters are not included in TypeScript’s type definitions, so calling function.length
does not count them.
function example(a: string, b: number = 10): void {}
console.log(example.length); // Output: 1 (not 2)
Using Default Parameters in Higher-Order Functions
Default parameters work well inside higher-order functions, especially when defining callbacks.
function processData(
data: string[],
callback: (item: string) => string = (item) => item.toUpperCase()
): string[] {
return data.map(callback);
}
console.log(processData(["apple", "banana"])); // Output: ["APPLE", "BANANA"]
console.log(processData(["apple", "banana"], (item) => `Fruit: ${item}`));
// Output: ["Fruit: apple", "Fruit: banana"]
Default Parameters with Object Destructuring
You can use default values when destructuring objects inside function parameters.
function configureSettings({ theme = "light", fontSize = 14 } = {}): void {
console.log(`Theme: ${theme}, Font size: ${fontSize}`);
}
configureSettings(); // Output: Theme: light, Font size: 14
configureSettings({ theme: "dark" }); // Output: Theme: dark, Font size: 14
TypeScript default parameters make function calls more convenient by handling missing arguments without additional checks. They improve code readability, reduce boilerplate, and allow for sensible defaults.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.