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

🧩 TypeScript — Optional Parameters: Write Flexible and Type-Safe Functions

🧲 Introduction – What Are Optional Parameters in TypeScript?

In TypeScript, optional parameters allow you to define function arguments that aren’t required when calling the function. These parameters are declared with a ? after the parameter name and help make your code more flexible, less error-prone, and easier to use, especially when dealing with functions that accept varying numbers of inputs.

🎯 In this guide, you’ll learn:

  • How to declare and use optional parameters
  • Syntax rules and parameter positioning
  • Differences between optional and default parameters
  • Real-world examples and best practices

🧾 Declaring Optional Parameters in TypeScript

To mark a parameter as optional, use the ? symbol after the parameter name.

✅ Syntax:

function greet(name: string, greeting?: string): string {
  return greeting ? `${greeting}, ${name}` : `Hello, ${name}`;
}

🔍 Usage:

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

Explanation:
The second parameter greeting is optional. If not provided, the function defaults to “Hello”.


🧠 Optional vs Required Parameters

In TypeScript, required parameters must come before optional parameters. Optional parameters cannot precede required ones unless default values are provided for the earlier ones.

❌ Incorrect:

// Error: A required parameter cannot follow an optional parameter
function send(message?: string, recipient: string) {}

✅ Correct:

function send(recipient: string, message?: string) {
  console.log(`${recipient} received: ${message ?? "No message"}`);
}

🔁 Optional vs Default Parameters

While both allow skipping arguments, default parameters assign a value if none is passed, whereas optional parameters may remain undefined.

🔹 Optional:

function showInfo(name: string, age?: number) {
  console.log(`${name}, Age: ${age}`);
}

🔹 Default:

function showInfo(name: string, age: number = 18) {
  console.log(`${name}, Age: ${age}`);
}

✅ Best practice: Use optional when the parameter is truly optional; use default values when you want predictable fallbacks.


📚 Real-World Examples of Optional Parameters

1️⃣ Logging Utility:

function log(message: string, context?: string) {
  console.log(context ? `[${context}] ${message}` : message);
}

log("Server started");               // Server started
log("User login", "AuthModule");     // [AuthModule] User login

2️⃣ Calculator with Optional Operator:

function calculate(a: number, b: number, operator?: string): number {
  switch (operator) {
    case "subtract": return a - b;
    case "multiply": return a * b;
    default: return a + b; // default operation
  }
}

console.log(calculate(5, 3));           // 8
console.log(calculate(5, 3, "multiply")); // 15

🛡️ Using Optional Parameters in Interfaces

Optional parameters can be used in function types declared in interfaces:

interface Formatter {
  format(value: string, locale?: string): string;
}

const formatter: Formatter = {
  format(value, locale) {
    return locale === "fr" ? `Bonjour, ${value}` : `Hello, ${value}`;
  }
};

⚠️ Common Mistakes & How to Avoid Them

❌ Mistake✅ Solution
Putting optional parameter before requiredAlways list optional parameters after required ones
Forgetting to handle undefinedUse default values or nullish coalescing (??) to avoid runtime errors
Treating all parameters as optionalUse optional only when the argument is truly non-essential

💡 Best Practices for Optional Parameters

  • ✅ Place all optional parameters after required ones
  • ✅ Handle undefined explicitly using conditional checks or ??
  • ✅ Use optional parameters to simplify overloaded function designs
  • ✅ Prefer default parameters when you want fallback values
  • ✅ Document behavior clearly to avoid confusion for function consumers

📌 Summary – Recap & Next Steps

Optional parameters in TypeScript make your functions more adaptable, clean, and robust. By defining which arguments are required and which are not, you help developers understand your function’s usage while maintaining full type safety.

🔍 Key Takeaways:

  • Use ? to declare optional parameters
  • Always place optional parameters after required ones
  • Optional ≠ default — they behave differently
  • Handle undefined when accessing optional values
  • Optional parameters enhance flexibility and reusability

⚙️ Real-world relevance: Useful in API design, utility functions, UI callbacks, event handling, and third-party SDKs.


❓ FAQs – Optional Parameters in TypeScript

❓ Can optional parameters be followed by required ones?
❌ No. Required parameters must come before optional ones unless default values are used.

❓ What happens if I don’t handle an optional parameter?
It may be undefined, leading to runtime errors if accessed blindly.

❓ Is undefined the same as not providing a parameter?
📌 In many cases, yes. If no value is passed, the parameter is undefined.

❓ Can I use optional parameters in arrow functions?
✅ Yes. You can define them just like in regular functions.

❓ Should I use optional or default parameters?
Use optional when the argument may not be needed. Use default when you want to ensure a fallback value.


Share Now :

Leave a Reply

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

Share

TypeScript — Optional Parameters

Or Copy Link

CONTENTS
Scroll to Top