Annotating for Documentation Value
What you'll learn: How to use explicit type annotations as living documentation, even when TypeScript already knows the type.
When Annotations Serve Readers, Not Compilers
By now, you know that TypeScript often infers types perfectly well. A variable like const count = 5 doesn't need : number — TypeScript already knows. But here's the insight: types aren't just for the compiler; they're for humans too.
Explicit annotations can make your code dramatically easier to understand, especially when:
- The inferred type is complex or non-obvious
- You're defining a public interface or exported function
- Future readers (including yourself) need to know intent, not just implementation
Documentation Through Annotations
Consider a function where TypeScript infers the return type:
function calculateDiscount(price: number, isVIP: boolean) {
return isVIP ? price * 0.8 : price * 0.95;
}
TypeScript knows this returns number. But adding the annotation helps readers:
function calculateDiscount(price: number, isVIP: boolean): number {
return isVIP ? price * 0.8 : price * 0.95;
}
Now anyone reading the signature immediately sees what comes out, without tracing through the logic.
The Readability Trade-off
This isn't about correctness — the inferred version works identically. It's about communication. When the annotation costs you nothing but a few keystrokes yet saves future readers mental effort, it's worth it.
Think of it like variable names: x works, but totalPrice documents intent.
Key Takeaway: Even when inference works, explicit type annotations serve as inline documentation that makes your code's contract instantly clear to human readers.