Lessons
TypeScript Tutorial
TypeScript Control Structures
TypeScript Function Types
Default Parameters in TypeScript
When writing reusable and scalable functions in TypeScript, default parameters can significantly simplify your code. But what exactly are default parameters? Why should you use them? And how do they differ from optional parameters?
This article answers all of that and more, with beginner-friendly examples, edge-case clarifications, and expert-backed insights that make this guide valuable for both new and experienced developers.
What Are Default Parameters in TypeScript?
Default parameters in TypeScript allow you to assign a predefined value to a function parameter. If a value isn't passed for that parameter when the function is called, the default value is used instead.
Why Use Default Parameters?
Default parameters improve your code in three key ways:
- They prevent undefined values from causing runtime errors.
- They simplify function calls, especially when only a few parameters change.
- They enhance code readability, making the developer’s intent clearer.
Here’s a quick example to demonstrate how they work:
typescript
1 2 3 4 5 6
function greet(name: string = "Guest") { console.log(`Hello, ${name}!`); } greet(); // Output: Hello, Guest! greet("Mishal"); // Output: Hello, Mishal!
💡 Personal Tip: Use default parameters when your function often uses a common value, like a fall back configuration or label.
How Do Default Parameters Work in TypeScript?
Default parameters behave similarly to those in JavaScript. The key difference is that TypeScript gives you static type checking and type inference benefits.
Parameter Order Matters
Default parameters must come after required ones, unless you're explicitly passing undefined
.
typescript
1 2 3 4 5 6
function showMessage(message: string, user: string = "Anonymous") { console.log(`[${user}]: ${message}`); } showMessage("Welcome!"); // [Anonymous]: Welcome! showMessage("Hello!", "Admin"); // [Admin]: Hello!
⚠️ If you place a default parameter before a required one and don’t pass any arguments, TypeScript will throw an error.
Using Expressions as Default Values
Default values can be dynamic expressions, not just static values.
typescript
1 2 3 4 5 6
function calculateTotal(price: number, tax: number = price * 0.2): number { return price + tax; } console.log(calculateTotal(100)); // 120 console.log(calculateTotal(100, 30)); // 130
This pattern is useful when one parameter depends on another, as seen in pricing or configuration logic.
Real-World Examples of TypeScript Default Parameters
Let’s look at a few scenarios where default parameters can simplify code in practical applications.
1. Logging Function with Default Severity
typescript
1 2 3 4 5 6
function logEvent(event: string, level: string = "info") { console.log(`[${level.toUpperCase()}]: ${event}`); } logEvent("Server started"); // [INFO]: Server started logEvent("Unauthorized access", "warn"); // [WARN]: Unauthorized access
2. API Request with Default Timeout
typescript
1 2 3 4
function fetchData(url: string, timeout: number = 5000) { // Simulate fetch console.log(`Fetching ${url} with timeout of ${timeout}ms`); }
Real Benefit: Saves users from repeating the same timeout value over and over.
3. Theme Configuration with Default Settings
typescript
1 2 3
function setupTheme(theme: string = "light") { console.log(`Applying ${theme} theme...`); }
These examples show how default parameters support real-world development needs—especially in libraries, SDKs, or enterprise applications.
Best Practices for Using Default Parameters
Here are some guidelines to keep your code clean and effective:
Avoid Mixing Too Many Default and Optional Params
Try not to overload a function with numerous optional/default parameters. Use objects with named properties for scalability.
Use (??) When Needed
If null
or undefined
are valid possibilities, prefer ??
instead of ||
.
python
1 2 3 4
function showRating(rating?: number) { const displayed = rating ?? 5; // Use 5 if rating is undefined or null console.log(`Rating: ${displayed}`); }
Document Defaults Clearly
Help other developers by indicating default values in comments or API documentation.
Common Pitfalls and How to Avoid Them
Placing Default Before Required Params
python
1 2 3 4
// ❌ Incorrect function log(level: string = "info", message: string) {} // ✅ Correct function log(message: string, level: string = "info") {}
Overusing Defaults for Objects or Arrays
Avoid using mutable objects as defaults unless cloned.
python
1 2 3
function init(config: object = {}) { // If shared across calls, could lead to bugs }
Final Thoughts
Default parameters in TypeScript are more than just a convenience—they're a practical tool for writing cleaner, more maintainable, and more user-friendly code. When used correctly, they help solve real developer problems by:
- Reducing the need for repetitive checks
- Clarifying your function’s intent
- Making APIs easier to consume
Personal Recommendation: Use default parameters whenever your function would otherwise require repetitive argument checks. They keep your code DRY (Don't Repeat Yourself) and self-documenting.