Function Parameters
TypeScript provides flexible parameter options: optional, default, and rest parameters, all with type safety.
Optional Parameters
Use ? to make parameters optional. Optional parameters can be
undefined:
Output
Click Run to execute your code
Important: Optional parameters must come AFTER required
parameters.
// ✗ Wrong
function greet(lastName?: string, firstName: string) { }
// ✓ Correct
function greet(firstName: string, lastName?: string) { }
Default Parameters
Default parameters have a fallback value if not provided:
Output
Click Run to execute your code
Tip: Default parameters are automatically optional. You don't
need to add
?
Optional vs Default Parameters
| Feature | Optional (?) |
Default (=) |
|---|---|---|
| Value if omitted | undefined |
Default value |
| Type includes undefined | Yes | No |
| Must check for undefined | Yes | No |
| Position requirement | After required | Anywhere |
Rest Parameters
Rest parameters collect multiple arguments into an array:
Output
Click Run to execute your code
Rest Parameter Rules:
- Must be the LAST parameter
- Only ONE rest parameter allowed
- Type must be an array
Common Mistakes
1. Wrong Parameter Order
// ✗ Wrong - optional before required
function create(id?: number, userName: string) { }
// ✓ Correct
function create(userName: string, id?: number) { }
2. Multiple Rest Parameters
// ✗ Wrong - only one rest parameter allowed
function combine(...nums: number[], ...strs: string[]) { }
// ✓ Correct - use union type
function combine(...items: (number | string)[]) { }
Summary
- Optional:
param?- can be undefined - Default:
param = value- has fallback - Rest:
...params- collects multiple args - Optional/rest must come after required parameters
What's Next?
Next: Function Overloading for multiple function signatures!
Enjoying these tutorials?