TypeScript · Types that pay for themselves
When should you add type annotations?
Short answer
Annotations explicitly declare the type of a variable, parameter, return value or property. They are erased at compile time and matter most at module boundaries and where inference is too wide.
An annotation is a contract. It tells the compiler and the reader what a value is supposed to be, and the compiler checks that assignments and calls respect it. Because annotations are erased, they have no runtime cost, but an inaccurate annotation can give false confidence.
function parseCount(input: string): number {
const value = Number(input);
if (Number.isNaN(value)) {
throw new Error("Invalid count");
}
return value;
}
const total: number = parseCount("42");Where annotations earn their keep
- Exported function parameters and return types
- Public class fields and method signatures
- Variables that start as null or undefined and are assigned later
- Callbacks whose parameter type cannot be inferred from context
- Data structures that are intentionally wider than their initial value
For local variables, inference is usually clearer. Writing const total: number = 0 next to const total = 0 adds noise without adding safety. The exception is when the initial value would infer a narrower type than the variable is meant to hold later.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Are type annotations emitted to JavaScript?
- 2Why annotate an exported function's return type?
- 3When does inference produce a type that is too narrow?
- 4How do annotations interact with strict mode?
Say it in the interview
Annotations declare a type explicitly on a variable, parameter, return value or property. They are erased at compile time, so they cost nothing at runtime. I annotate exported APIs and places where inference would be too wide, but I avoid annotating every local because it adds noise. The compiler still checks that the annotation and the assigned value agree.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.