TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
addTip(40, "5") returns 405 in JavaScript with no error. TypeScript stops it before it runs. Annotations, inference, interfaces, optional properties, unions with narrowing, generics vs any, and type vs interface, with real tsc messages.
What you will learn
- Explain that tsc checks types before anything runs and then erases them
- Write annotations where they help and rely on inference elsewhere
- Describe object shapes with interfaces and optional properties, and read tsc errors
- Narrow unions with typeof, in and a kind field, and keep types with generics instead of any
Before you start
- JavaScript syntax: const, arrow functions, objects
- npm and running tools with npx
TypeScript is JavaScript with types, and the whole idea fits in one line: the types are checked before your code runs, and then they're erased. Let's start with a tiny bug.
JavaScript finds the bug too late
// Plain JavaScript: nothing checks what goes in.
function addTip(bill, tip) {
return bill + tip;
}
// The tip came from a text box, so it is text.
const total = addTip(40, "5");
console.log("Total to pay:", total);
console.log("Total times two:", total * 2);
Total to pay: 405
Total times two: 810
The tip came from a text box, so it's the string "5". 40 + "5" glues the two together into "405". Then * 2 turns that text back into a number, 810. There's no error at all, just a wrong answer that a user finds, not you.
TypeScript stops it before it runs
// The same function, with types on the way in and out.
function addTip(bill: number, tip: number): number {
return bill + tip;
}
// tsc stops here: "5" is a string, not a number.
const total = addTip(40, "5");
console.log("Total to pay:", total);
npx tsc --noEmit tip.ts
tip.ts(7,26): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
Now each parameter says what may go in: bill: number, tip: number, and : number after the brackets for what comes out. The 40 fits the first slot; the string "5" bounces off the second. tip.ts(7,26) means line 7, column 26, exactly where "5" starts, and TS2345 is the error number. tsc only read the file. Nothing ran, so the bug never reached a user.
Checked first, then erased
// Types are checked first, then erased.
function addTip(bill: number, tip: number): number {
return bill + tip;
}
const tip: number = 5;
const total = addTip(40, tip);
console.log("Total to pay:", total);
This is the file tsc wrote:
"use strict";
// Types are checked first, then erased.
function addTip(bill, tip) {
return bill + tip;
}
const tip = 5;
const total = addTip(40, tip);
console.log("Total to pay:", total);
Total to pay: 45
Every : number is gone, and "use strict" was added because strict mode is on. Node never sees a single type. That has a practical consequence. The tool tsx runs a TypeScript file directly by stripping the types without checking them, so give it the broken tip.ts and it happily prints Total to pay: 405. Only tsc (or your editor, which runs the same checker) catches type mistakes, and only before the code runs.
Annotations and inference
// Annotation: you write the type after a colon.
const student: string = "Emma";
const scores: number[] = [82, 91, 67];
// Inference: no annotation, TypeScript works it out.
let best = 0;
const city = "Boston";
function average(values: number[]): number {
const sum = values.reduce((a, v) => a + v, 0);
return sum / values.length;
}
const avg = average(scores);
best = Math.max(...scores);
console.log(student, "from", city, "best:", best);
console.log("Average:", avg.toFixed(1));
Emma from Boston best: 91
Average: 80.0
student: string and scores: number[] are annotations: the type after a colon. let best = 0 has none, but TypeScript infers it; hover over it and the editor says let best: number. const city = "Boston" shows as const city: "Boston", the exact text, because a const never changes. And avg is inferred as number from average's return type.
Inferred types are guarded just the same. Add best = "high"; and tsc says Type 'string' is not assignable to type 'number'. Write types where they help a reader, such as parameters and return values, and let TypeScript infer the rest.
An interface is a shape
// An interface is the shape an object must have.
interface Task {
id: number;
title: string;
done: boolean;
owner?: string; // ? = optional: may be missing
}
const report: Task = {
id: 1, title: "Report", done: true, owner: "Jack",
};
const trip: Task = {
id: 2, title: "Trip", done: false,
};
function describe(task: Task): string {
const owner = task.owner ?? "nobody";
return `#${task.id} ${task.title} (${owner})`;
}
console.log(describe(report));
console.log(describe(trip));
#1 Report (Jack)
#2 Trip (nobody)
Task is the shape an object must have: four slots with a type each. report fills all four. trip has no owner, which is fine because owner? has a question mark, meaning optional.
Now two objects that don't fit:
// missing: done is not optional
const rent: Task = { id: 3, title: "Rent" };
// wrong type: done must be a boolean
const tax: Task = { id: 4, title: "Tax", done: "no" };
misfit.ts(10,7): error TS2741: Property 'done' is missing in type '{ id: number; title: string; }' but required in type 'Task'.
misfit.ts(13,42): error TS2322: Type 'string' is not assignable to type 'boolean'.
tsc names what's wrong and where: the missing property on line 10, and the string in a boolean slot at line 13, column 42.
Optional means maybe undefined
owner?: string really means "string or undefined". That's why describe uses task.owner ?? "nobody". Skip the check and write trip.owner.toUpperCase(), and tsc stops you:
error TS18048: 'trip.owner' is possibly 'undefined'.
Run it anyway with tsx and it crashes with TypeError: Cannot read properties of undefined (reading 'toUpperCase'). TypeScript makes you handle the missing case.
Unions, narrowed
// A union: id is ONE of these types at a time.
function show(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // here: string
}
return "ORDER-" + id.toFixed(0); // here: number
}
console.log(show("ab12"));
console.log(show(7));
AB12
ORDER-7
string | number is a union: one of the two at a time. Inside the typeof id === "string" branch, TypeScript shrinks the type to string, so toUpperCase is allowed. After that branch returns, only number is left, so toFixed is allowed. That shrinking is called narrowing. Without a check, id.toUpperCase() fails:
error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.
Unions of object shapes use a shared field to tell them apart:
// A discriminated union: "kind" tells the two apart.
type Card = { kind: "card"; last4: string };
type Cash = { kind: "cash"; amount: number };
type Payment = Card | Cash;
function receipt(p: Payment): string {
if (p.kind === "card") {
return "Card ending " + p.last4; // p: Card
}
return "Cash " + p.amount.toFixed(2); // p: Cash
}
function method(p: Payment): string {
return "last4" in p ? "card" : "cash"; // in narrows
}
const paid: Payment = { kind: "cash", amount: 20 };
console.log(receipt(paid), method(paid));
console.log(receipt({ kind: "card", last4: "4242" }));
Cash 20.00 cash
Card ending 4242
Both shapes have kind with a different exact text. Checking p.kind === "card" narrows Payment to Card, so p.last4 is allowed; otherwise it's Cash and p.amount is allowed. "last4" in p narrows the same way by asking whether the property exists. A typo is caught too: receipt({ kind: "cheque", amount: 5 }) gives Type '"cheque"' is not assignable to type '"card" | "cash"'.
Generics: a type slot
// A generic: T is a type slot, filled in on each use.
interface Box<T> {
value: T;
}
function box<T>(value: T): Box<T> {
return { value };
}
const n = box(42); // T = number
const s = box("Sophie"); // T = string
console.log(n.value + 1);
console.log(s.value.toUpperCase());
43
SOPHIE
T is an empty type slot. Each call fills it from the value you pass: box(42) gives a Box<number>, box("Sophie") a Box<string>. TypeScript remembers, so n.value.toUpperCase() is caught with Property 'toUpperCase' does not exist on type 'number'. (At run time it would be TypeError: n.value.toUpperCase is not a function.)
Why not just use any?
// T follows the array you pass in; any forgets it.
function first<T>(items: T[]): T {
return items[0];
}
function firstAny(items: any[]): any {
return items[0];
}
const level = first([3, 1, 2]); // number
const who = first(["Emma", "Liam"]); // string
const loose = firstAny([3, 1, 2]); // any
console.log(level + 1, who.toUpperCase());
console.log(typeof loose);
4 EMMA
number
first keeps the type: level is a number and who is a string, so level.toUpperCase() is caught. firstAny throws the type away. loose is any, tsc says nothing about loose.toUpperCase(), and it crashes at run time with TypeError: loose.toUpperCase is not a function. A generic keeps the type of what you pass in; any forgets it and the mistake waits for run time.
type or interface?
// interface: an object shape, can be extended.
interface User {
name: string;
}
interface Admin extends User {
level: number;
}
// type: any type at all, joined with &.
type Id = string | number;
type Staff = User & { team: string };
const a: Admin = { name: "Emma", level: 2 };
const s: Staff = { name: "Liam", team: "Ops" };
const id: Id = 7;
console.log(a.name, s.team, id);
Emma Ops 7
Admin extends User gets name from User and adds level. Staff does the same idea with type and &. Only type can name a union like Id = string | number. The simple rule: interface for object shapes, especially ones you extend; type for unions and everything else.
Quick recap
| Idea | Remember |
|---|---|
tsc | checks before anything runs; node never sees a type; tsx skips the check |
| Annotation / inference | annotate parameters and returns, let the rest be inferred |
interface | the shape an object must have; errors come with line and column |
owner? | may be undefined; handle it with ?? or a check |
| Union + narrowing | typeof, in or a kind field shrinks the type |
Generic <T> | a type slot filled on each use; any forgets |
type vs interface | interface for objects, type for unions |
Python type hints are the closest match: str | int, Optional, TypedDict and generics, checked by a separate tool and ignored at run time. The difference is that TypeScript projects usually make the check part of the build, as tsc && vite build does in npm, packages and Vite. Later in the course, the TypeScript types for a React client are generated straight from a FastAPI spec: see generating a TypeScript client with Orval.
Try it yourself
Add a third payment shape, { kind: "voucher"; code: string }, to Payment. Run npx tsc --noEmit payments.ts and see whether receipt still compiles, then add a branch for it so every kind returns the right text.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
