Best Practices for Inference vs Explicit Types
What you'll learn: How to decide when to let TypeScript infer generic type arguments versus when to explicitly specify them for better code clarity.
The Judgment Call
By now you've seen that TypeScript can infer type arguments from your function calls, and you can also explicitly provide them with angle brackets. The question is: when should you do which?
Think of it like driving directions. Sometimes "turn at the gas station" (inference) is perfectly clear. Other times you need "turn left at 1234 Main Street" (explicit types) to avoid confusion.
When to Rely on Inference
Let TypeScript do the work when:
- The type is obvious from the arguments you're passing
- Writing it explicitly would just repeat what's already clear
- The inference result matches your intent
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
// Inferred: number[] — obvious and correct
When to Be Explicit
Provide type arguments when:
- Inference fails or produces
unknownor overly broad types - You want to enforce a specific type for safety (e.g., narrowing to a literal union)
- The code is clearer when readers see the expected type upfront
- You're working with empty collections that need a specific type
const ids = new Set<string>();
// Explicit: prevents accidental number insertions later
const data = parseJSON<User>(responseText);
// Explicit: makes API contract visible at call site
Key Takeaway: Prefer inference for brevity and flexibility, but use explicit type arguments whenever they add clarity, prevent mistakes, or document intent that isn't obvious from the code alone.