Why Types: Annotations, Inference and the Compiler
See what static types add to JavaScript, where inference works and where it needs annotations, and run the compiler the way a real project does.
Contentsand lesson path
On this page
- Why it matters
- Inference does most of the work
- Where inference needs your help
- Types are erased before your code runs
- Running the compiler
- Check your understanding
- Apply it
- Review prompt
Lessons of TypeScript Foundations
- Why Types: Annotations, Inference and the Compiler Concept · 20 min
- Modeling Data with Unions, Literals and Interfaces Worked example · 25 min
- Narrowing and Validating Data You Do Not Control Worked example · 25 min
- Generics and Types Built from Other Types Concept · 25 min
- Lab: Convert a JavaScript Module to Strict TypeScript Lab · 30 min
- Check: Type Puzzles and Compiler Errors Knowledge check · 8 questions
What you will learn
- Annotate functions, objects and arrays where inference is not enough, and model domain data with type aliases, interfaces, literal types and unions.
- Configure a strict tsconfig, run type checks as part of the build, and consume typed third-party packages and declaration files.
Prerequisites: JavaScript Foundations
01. Why it matters
JavaScript checks nothing until the code runs. A misspelled property name is not an error to JavaScript: reading a property that does not exist simply produces undefined, and the failure surfaces somewhere else, as the wrong output or a crash far from the cause. Run this plain JavaScript file:
function format(invoice) {
return `${invoice.id}: ${(invoice.cents / 100).toFixed(2)}`;
}
console.log(format({ id: 'INV-9', centes: 4200 }));INV-9: NaNNo error, no warning: just NaN on the invoice. The misspelled centes key and the cents the function reads are two separate mistakes that cancel out into silence. TypeScript is JavaScript plus a type layer that the compiler checks before your code runs. A type describes which values are allowed: this variable is a string, that array holds number values, this object always has an id property. The same file, typed:
function format(invoice: { id: string; cents: number }): string {
return `${invoice.id}: ${(invoice.cents / 100).toFixed(2)}`;
}
console.log(format({ id: 'INV-9', centes: 4200 }));typo.ts(5,35): error TS2561: Object literal may only specify known
properties, but 'centes' does not exist in type
'{ id: string; cents: number; }'. Did you mean to write 'cents'?The compiler points at the exact character, names both sides of the mismatch, and even suggests the fix. Nothing ran; the mistake never reached a user. That is the whole deal: you describe the shape of your data once, and every place that uses it is checked against the description. On a codebase of thousands of files, types become a checkable specification — of function parameters, API payloads and component props alike.
02. Inference does most of the work
You do not annotate everything. TypeScript works out types from the values it can see: a variable from its initialiser, a callback parameter from the function it is passed to, a call result from the function it calls. The annotation : number is only needed where the compiler has nothing to work from. Watch what inference catches when code misuses a value:
const rate = 0.2;
const tags = ['css', 'html'];
const order = { id: 'A-1042', paid: true };
// Try to use each value as a different type:
rate.toUpperCase();
tags.push(42);
order.paid = 'yes';inference.ts(6,6): error TS2339: Property 'toUpperCase' does not exist
on type '0.2'.
inference.ts(7,11): error TS2345: Argument of type 'number' is not
assignable to parameter of type 'string'.
inference.ts(8,1): error TS2322: Type 'string' is not assignable to
type 'boolean'.Three lines, three errors, no annotations written. Two details are worth noticing. Because rate is a const primitive, its type is the literal 0.2, so even a different number would be rejected — types track what the code guarantees, not just the category. And tags.push(42) fails because inference fixed the element type to string the moment the array was created. Inference is not a weak fallback; for locals, it is usually better than an annotation, because it can never drift out of date.
03. Where inference needs your help
Inference has blind spots, and they all come from the same cause: there is no value to read the type from. A declared function has a body, but its parameters could be called with anything, so under strict mode the compiler refuses to guess. That policy has a name, noImplicitAny, and it is the difference between types that protect you and types that quietly stop looking:
function area(w, h) {
return w * h;
}
area(3, 4);implicit-any.ts(1,15): error TS7006: Parameter 'w' implicitly has an
'any' type.
implicit-any.ts(1,18): error TS7006: Parameter 'h' implicitly has an
'any' type.The type any means "stop checking" — any value fits, and every operation on it compiles. strict makes implicit any an error so that the holes are at least visible ones. Annotate what inference cannot know, and let inference handle the rest:
const scores: number[] = []; // empty: nothing to infer from
let loadState: 'idle' | 'loading' = 'idle';
function total(price: number, quantity: number): number {
return price * quantity;
}
const paid = total(120, 2);
loadState = 'loading';
console.log(paid, loadState, scores.length);240 loading 0Three annotations, each earning its place. The empty array has no elements, so its element type must be declared. The variable loadState is restricted to two named values — a union of literal types, which the next lesson develops. The function parameters are checked at every call site, and the return type is stated so that a future edit that changes what total returns fails loudly here rather than silently somewhere else. A good working rule: annotate function boundaries; let inference fill the inside.
04. Types are erased before your code runs
TypeScript adds no checks at runtime. Compiling removes every type — the output is plain JavaScript that does exactly what your code says, with the types gone; nothing checks at runtime that the types were true:
interface Invoice {
id: string;
cents: number;
}
function format(invoice: Invoice): string {
return `${invoice.id}: ${(invoice.cents / 100).toFixed(2)}`;
}
console.log(format({ id: 'INV-9', cents: 4200 }));"use strict";
function format(invoice) {
return `${invoice.id}: ${(invoice.cents / 100).toFixed(2)}`;
}
console.log(format({ id: 'INV-9', cents: 4200 }));INV-9: 42.00The interface and the annotations are gone. The one added line, "use strict";, comes from the compiler: TypeScript 7 adds it to every output file that is not a module. It switches on JavaScript's strict mode in the engine, and it checks no types. Erasure has two consequences you will meet constantly. First, an annotation or a cast is a promise, not a check: writing data as Invoice tells the compiler to trust you, and it will. Data that arrives from outside the program — a JSON response, localStorage, a URL parameter — must be checked at runtime before its type can be believed, which is the subject of Narrowing and validating data you do not control. Second, the compiler and the bundler are separate tools: a bundler such as Vite strips types for speed and does not check them, so a project needs tsc --noEmit as its own step. That setup is the last section here and a running theme of this skill.
05. Running the compiler
A project describes its type-checking rules in tsconfig.json. The single most important setting is strict, which turns on the full set of checks, including noImplicitAny. TypeScript 6.0 and later turn it on by default; writing it out keeps the intent visible and makes older compilers behave the same. Every option is documented in the TSConfig Reference; this is the honest minimum this course uses:
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"noEmit": true
}
}npx tsc --noEmit # check every file, emit nothing
npx tsc --noEmit --watch # re-check on every saveexit code: 0 (no output means no type errors)Two habits make the check worth having. Run it on the whole project, not one file: types live in imports, so a per-file check sees only part of the truth. And make it fail a build: tsc --noEmit in the build script or CI is what stops a type error from reaching main, because the editor shows errors whether or not anyone looks. noEmit reflects the modern split of work — the compiler only judges, while the bundler (Vite, or the one inside Next.js) produces the JavaScript your users run. The lab at the end of this skill walks through exactly this setup on a real module.
06. Check your understanding
07. Apply it
Add the tsconfig.json from this lesson to a small JavaScript project of yours — the filtering module from the search-as-you-type lab is a good candidate. Set allowJs and checkJs to true first and run npx tsc --noEmit to see what the compiler says about your JavaScript as it is today. List the errors it finds and sort them into two groups: places where an annotation is genuinely missing, and places where the code has a latent bug that JavaScript never surfaced. This exercise is the first half of the skill practice — converting that search UI to strict TypeScript — which the lab completes.
08. Review prompt
Without looking back: what does the compiler report for area(w, h) under strict, and why does it refuse to guess? Name the three places in this lesson where an annotation earns its keep. Finally, explain to a colleague why a clean tsc --noEmit run tells you nothing about what a server actually sent your program.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.