Type Inference
Type inference lets the compiler derive a type from a value or expression. If you write const count = 3, TypeScript knows count is the literal type 3 in many contexts; a let variable is usually widened to number because it can be reassigned. Inference reduces noise while preserving checks.
Annotate when a type is not obvious, when you want a stable public contract, or when inference would be too narrow or too broad. Function parameter types generally need annotations unless contextual typing supplies them, such as in callbacks passed to typed APIs.
Inference and contextual typing
const appName = "Bytes4Dev";
let requestCount = 0;
const names = ["Asha", "Ravi"].map((name) => name.toUpperCase());
// name is inferred as string; names is string[]💡 The compiler infers
appName, requestCount, the array element type, and the callback parameter. Contextual typing supplies name: string from map's array signature.Key Takeaways
- Inference often makes explicit annotations unnecessary.
- Use annotations to clarify contracts, not to repeat every inferred type.
- Contextual typing provides types from the surrounding API.
Knowledge Check
What does TypeScript generally do when a callback is passed to a well-typed `map` call?