Course contentsShow
← TypeScript
Lesson 254 of 1,7966. FunctionsFree lesson

Type Annotations with Defaults

When and why to add explicit type annotations even when a parameter has a default value.

Type Annotations with Defaults

You'll learn: When and why to explicitly annotate types even when default values already provide them.

The Apparent Redundancy

You've learned that default parameters are implicitly optional and that TypeScript infers types from default values. So if you write function greet(name = "Guest"), TypeScript already knows name is a string. Why would you ever write function greet(name: string = "Guest")?

Why Add Explicit Annotations with Defaults

1. Documentation and Intent
The annotation makes your contract crystal clear to other developers (and your future self). It says "this parameter expects a string" without requiring readers to inspect the default value.

2. Catch Default Value Mistakes
If you accidentally write age = "30" when you meant age: number = 30, TypeScript catches your error immediately. Without the annotation, TypeScript infers string and you might not notice until runtime.

3. Complex Default Values
When defaults come from expressions or constants defined elsewhere, the explicit type serves as validation: timeout: number = DEFAULT_TIMEOUT ensures the constant matches your intent.

4. Team Coding Standards
Some teams prefer consistency: always annotate function parameters, even with defaults, to maintain uniform code style.

The Trade-off

Adding : string to name = "Guest" is technically redundant for simple cases. TypeScript doesn't need it. But code is read far more often than written—that extra clarity often pays for itself.

Key Takeaway: While TypeScript infers types from default values, explicit annotations improve readability, catch default value errors, and document your intent—especially valuable in team codebases or when defaults come from external constants.