6️⃣ 🧠 Functions in TypeScript
Estimated reading: 4 minutes 25 views

⚙️ TypeScript — Default Parameters: Simplify Function Calls with Safe Defaults

🧲 Introduction – What Are Default Parameters in TypeScript?

In TypeScript, default parameters allow you to assign default values to function parameters, so callers can omit arguments without causing errors. This feature simplifies function usage and ensures that functions behave predictably even when some parameters are not provided.

Default parameters are especially useful in cases where certain inputs are optional, but should fall back to a known safe or common value if not supplied.

🎯 In this guide, you’ll learn:

  • How to declare default parameters in TypeScript
  • Behavior with undefined, null, and missing values
  • Differences between default and optional parameters
  • Real-world examples and best practices

🧾 Declaring Default Parameters in TypeScript

To assign a default value to a parameter, simply use the = operator in the function signature.

✅ Syntax:

function greet(name: string = "Guest"): string {
  return `Hello, ${name}`;
}

🔍 Usage:

console.log(greet());        // Hello, Guest
console.log(greet("Alice")); // Hello, Alice

Explanation:

  • If no argument is passed, "Guest" is used as the default.

🔄 Default Parameters with Other Arguments

Default parameters can appear anywhere, but must follow required parameters unless explicitly handled.

function sendMessage(to: string, message: string = "Hello"): void {
  console.log(`${to} receives: ${message}`);
}

sendMessage("Bob");                  // Bob receives: Hello
sendMessage("Alice", "Good day!");   // Alice receives: Good day!

🧱 Behavior with undefined vs null

  • Passing undefined triggers the default value.
  • Passing null does not trigger the default—it is treated as a value.

✅ Example:

function logInfo(level: string = "info") {
  console.log(`[${level}] Logging event`);
}

logInfo(undefined); // [info] Logging event
logInfo(null);      // [null] Logging event

📌 Tip: Only omit the argument or pass undefined to trigger the default.


🧩 Default vs Optional Parameters

FeatureDefault ParameterOptional Parameter
Declared with= (e.g., param = "value")? (e.g., param?)
Value if omittedUses defaultundefined
Value if passed nullRemains nullRemains null
Type requirementStill requires matching typeAccepts undefined as valid input

🔁 Combining Default and Optional Parameters

You can mix both types, but always place required parameters first, followed by default and then optional.

function register(username: string, role: string = "user", bio?: string) {
  console.log(`Username: ${username}, Role: ${role}, Bio: ${bio ?? "N/A"}`);
}

register("Alice");                        // Username: Alice, Role: user, Bio: N/A
register("Bob", "admin", "Developer");    // Username: Bob, Role: admin, Bio: Developer

🧠 Real-World Examples of Default Parameters

📬 Email sender:

function sendEmail(to: string, subject: string = "No Subject") {
  console.log(`Email sent to ${to} with subject: ${subject}`);
}

🔢 Number formatter:

function formatNumber(value: number, decimals: number = 2): string {
  return value.toFixed(decimals);
}

console.log(formatNumber(3.14159)); // 3.14

⚠️ Common Mistakes & How to Avoid Them

❌ Mistake✅ Solution
Using default parameter before requiredAlways declare default parameters after required ones
Assuming null uses defaultOnly undefined or missing arguments trigger the default value
Overusing default valuesUse only when fallback behavior is clearly necessary

💡 Best Practices for Default Parameters

  • ✅ Use default values when a reasonable fallback exists
  • ✅ Combine with optional parameters for maximum flexibility
  • ✅ Keep parameter order logical (required → default → optional)
  • ✅ Avoid complex expressions as default values—keep them simple
  • ❌ Don’t rely on default values for mandatory logic

📌 Summary – Recap & Next Steps

Default parameters in TypeScript provide a clean and safe way to handle missing arguments in functions. They enhance your code by making it more flexible, concise, and user-friendly—without sacrificing type safety.

🔍 Key Takeaways:

  • Use = to declare default values in function parameters
  • Default values are used when a parameter is omitted or undefined
  • Default parameters must follow required parameters
  • Combine with optional parameters for adaptable function signatures

⚙️ Real-world relevance: Used in API utilities, configuration functions, logging tools, UI behavior, and backend controllers.


❓ FAQs – Default Parameters in TypeScript

❓ Are default parameters required or optional?
✅ Optional. You can call the function without passing the defaulted parameter.

❓ What triggers the default value?
📌 Only if the argument is omitted or explicitly undefined.

❓ Can I use an object or array as a default parameter?
✅ Yes, but be cautious—it may create shared references unless cloned inside the function.

❓ Can default parameters come before required ones?
❌ No. Default parameters must follow all required parameters.

❓ What’s better: optional or default parameters?
Use default when you want a known fallback; use optional when the value is truly not required.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript — Default Parameters

Or Copy Link

CONTENTS
Scroll to Top