Optional Parameters Must Come Last
You'll learn: Why TypeScript forces you to declare optional parameters after all required ones, and what error you'll hit if you don't.
When you define a function with optional parameters (using ?), TypeScript enforces a strict ordering rule: all optional parameters must come after all required parameters. You cannot place a required parameter after an optional one.
Why This Rule Exists
Think of it like ordering food at a restaurant. If the waiter asks "What would you like to eat?" (required), then "Would you like a drink?" (optional), and finally "What's your name?" (required), it creates confusion. You'd naturally expect all required questions upfront.
In function calls, JavaScript passes arguments by position. If you could mix optional and required parameters, the compiler wouldn't know which arguments map to which parameters when some are omitted:
// ❌ This causes an error
function greet(firstName?: string, lastName: string) {
console.log(`Hello ${firstName} ${lastName}`);
}
// If allowed, how would TypeScript interpret this?
greet("Smith"); // Is "Smith" the firstName or lastName?
The error you'd see: "A required parameter cannot follow an optional parameter."
The Correct Order
Always place required parameters first, optional parameters last:
// ✅ Correct ordering
function greet(lastName: string, firstName?: string) {
console.log(`Hello ${firstName || ''} ${lastName}`);
}
greet("Smith"); // Works
greet("Smith", "John"); // Works
Key Takeaway: Optional parameters must always come after all required parameters to maintain positional clarity in function calls.