Most types are shapes of objects
Most of the data in a real program is objects: a user, an order, a forecast, a configuration, an API response. Describing their shapes, once, in one place, is where TypeScript earns most of its keep. Every function that receives an order is checked against the same description; every misspelled field is caught; and when the shape changes (say, email becomes optional), the compiler lists every place that must be updated. That last point is why teams find large refactorings far less frightening in TypeScript than in JavaScript.
TypeScript gives you two ways to name a shape, interface and type, and they overlap so much that the choice confuses newcomers. This lesson covers the building blocks first, then the differences and the conventions teams actually follow.
Interfaces
// Interfaces describe object shapes: required, optional and read-only properties, and methods.
interface Address {
street: string;
city: string;
postcode?: string; // optional: may be missing
}
interface Person {
readonly id: number; // cannot be reassigned after creation
name: string;
email?: string;
address: Address;
greet(greeting: string): string; // a method
}
// An interface can extend one or more others.
interface Employee extends Person {
team: string;
startYear: number;
}
const amaka: Employee = {
id: 101,
name: "Amaka Obi",
address: { street: "12 Allen Avenue", city: "Lagos" },
team: "Payments",
startYear: 2021,
greet(greeting) { // parameter type comes from the interface
return `${greeting}, I'm ${this.name} from ${this.team}.`;
},
};
function mailingLabel(p: Person): string {
const lines = [p.name, p.address.street, p.address.city];
if (p.address.postcode !== undefined) lines.push(p.address.postcode);
return lines.join(" / ");
}
console.log(amaka.greet("Hello"));
console.log(mailingLabel(amaka)); // an Employee is a Person
console.log(amaka.email ?? "(no email on file)");
console.log(Object.keys(amaka).length);
export {};Hello, I'm Amaka Obi from Payments.
Amaka Obi / 12 Allen Avenue / Lagos
(no email on file)
6The pieces:
- Properties are listed with their types, separated by semicolons (commas also work). Nesting is natural:
address: Addressuses another interface. - Optional properties (
postcode?: string) may be absent. Reading one givesstring | undefined, somailingLabelmust check before using it, exactly as with the optional parameters of the last lesson. readonlyproperties can be set when the object is created but not reassigned afterwards:p.id = 2is rejected withCannot assign to 'id' because it is a read-only property. Likereadonlyarrays, this is a compile-time promise only.- Methods can be written as
greet(greeting: string): string. In the object literal, the parametergreetingneeds no annotation: its type comes from the interface, an example of contextual typing. extendsbuilds a new interface from existing ones, andEmployeeis assignable toPerson(somailingLabel(amaka)works) because it has everything aPersonhas. An interface may extend several others:interface Manager extends Employee, Approver { ... }. If the extension contradicts its parent, TypeScript says so at the declaration.
interface Tagged { id: string }
interface Counted extends Tagged { id: number }main.ts(2,11): error TS2430: Interface 'Counted' incorrectly extends interface 'Tagged'.
Types of property 'id' are incompatible.
Type 'number' is not assignable to type 'string'.The indented lines under the first one are typical of TypeScript's messages for nested types: each level explains the one above, so read from the top down until you reach the property that actually disagrees.
Type aliases and intersections
Definition— type alias and intersection
A type alias, type Name = ..., gives a name to any type: an object shape, a union, a tuple, a function type, a primitive. An intersection, A & B, is the type of values that belong to both A and B; for object types, that means having all the properties of both.
// Type aliases name any type: unions, tuples, functions, and object shapes too.
type ID = string | number;
type Point = { x: number; y: number };
type Pair<T> = [T, T];
type Formatter = (value: number) => string;
// Intersections (&) combine object types: a value must satisfy both.
type Timestamped = { createdAt: string; updatedAt: string };
type Note = { id: ID; text: string } & Timestamped;
// Index signatures and Record: objects used as dictionaries.
type Inventory = { [sku: string]: number };
type ScoresByPlayer = Record<string, number[]>;
// Indexed access: look up the type of a property.
type NoteText = Note["text"]; // string
const note: Note = {
id: 7,
text: "Buy cardamom",
createdAt: "2026-11-19T08:00:00Z",
updatedAt: "2026-11-19T09:15:00Z",
};
const corners: Pair<Point> = [{ x: 0, y: 0 }, { x: 4, y: 3 }];
const asPercent: Formatter = (v) => `${(v * 100).toFixed(1)}%`;
const stock: Inventory = { "TEA-01": 40, "HNY-02": 12 };
const scores: ScoresByPlayer = { Lin: [7, 9], Omar: [8] };
const firstLine: NoteText = note.text.toUpperCase();
const [a, b] = corners;
console.log(note.id, firstLine, note.updatedAt.slice(0, 10));
console.log(Math.hypot(b.x - a.x, b.y - a.y), asPercent(0.4567));
stock["SAF-03"] = 5; // any string key is allowed
console.log(Object.entries(stock).map(([sku, n]) => `${sku}:${n}`).join(" "));
console.log(Object.values(scores).flat().length);
export {};7 BUY CARDAMOM 2026-11-19
5 45.7%
TEA-01:40 HNY-02:12 SAF-03:5
3- Function types are written like arrow functions:
(value: number) => string. The parameter name is documentation; only the types matter. Pair<T>has a type parameter, soPair<Point>is a tuple of two points. That is a generic type, the subject of lesson six.- Intersections compose shapes:
Noteis the note's own fields and the timestamps. Mixing in a shared piece likeTimestampedacross many types is a common pattern. If the parts disagree, the intersection is quietly impossible rather than an error at the declaration: in{ id: string } & { id: number },idwould have to be both a string and a number, so its type isnever, and the error appears only when you try to create a value:Type 'string' is not assignable to type 'never'. That is one reasonextends, which reports the conflict where it is written, gives better errors. - Index signatures (
{ [sku: string]: number }) andRecord<K, V>describe objects used as dictionaries: any string key, values of one type. The two forms are equivalent here;Recordis shorter and also accepts a union of literal keys, as inRecord<"low" | "high", number>, which requires exactly those keys. - Indexed access (
Note["text"]) looks up the type of a property, so a type can follow another without repeating it. Changetextto something else inNoteandNoteTextfollows.
There is a gap in the dictionary types worth knowing about now. Reading stock["NOPE"] has type number, although at run time the result is undefined. The option noUncheckedIndexedAccess, covered in lesson nine, makes such reads number | undefined and forces a check, which is safer; the tsc --init configuration you saw in lesson one turns it on.
Worked example: typing an API response
The most common first job for interfaces in a real project is describing the JSON that a service sends back. Here is a departure board for one bus stop, typed and then used:
// Typing an API response: a departure board for one bus stop.
interface Departure {
route: string;
destination: string;
scheduled: string; // "HH:MM", local time
delayMinutes?: number; // absent when the bus is on time
accessible: boolean;
}
interface StopBoard {
stop: { id: string; name: string; zone: "A" | "B" | "C" };
departures: Departure[];
}
// In real code this object would come from fetch(...).then((r) => r.json()),
// and would be validated before being trusted (see lesson nine).
const board: StopBoard = {
stop: { id: "MX-0412", name: "Mercado Juárez", zone: "B" },
departures: [
{ route: "12", destination: "Centro", scheduled: "08:05", accessible: true },
{ route: "7A", destination: "Universidad", scheduled: "08:09", delayMinutes: 4, accessible: false },
{ route: "12", destination: "Centro", scheduled: "08:20", delayMinutes: 1, accessible: true },
],
};
function addMinutes(time: string, minutes: number): string {
const [h, m] = time.split(":").map(Number);
const total = h * 60 + m + minutes;
return `${String(Math.floor(total / 60) % 24).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
}
function describeDeparture(d: Departure): string {
const delay = d.delayMinutes ?? 0;
const when = delay === 0 ? d.scheduled : `${addMinutes(d.scheduled, delay)} (+${delay})`;
return `${d.route.padEnd(3)} ${d.destination.padEnd(12)} ${when}${d.accessible ? " ♿" : ""}`;
}
function averageDelay(departures: readonly Departure[]): number {
if (departures.length === 0) return 0;
const total = departures.reduce((sum, d) => sum + (d.delayMinutes ?? 0), 0);
return total / departures.length;
}
console.log(`${board.stop.name} [zone ${board.stop.zone}]`);
for (const d of board.departures) console.log(describeDeparture(d));
console.log(`average delay: ${averageDelay(board.departures).toFixed(1)} min`);
export {};Mercado Juárez [zone B]
12 Centro 08:05 ♿
7A Universidad 08:13 (+4)
12 Centro 08:21 (+1) ♿
average delay: 1.7 minLook at how the types shape the code. delayMinutes is optional, so both describeDeparture and averageDelay are forced to decide what a missing delay means (here, on time), instead of quietly producing NaN for the first bus. zone is a union of three letters, so a typo such as "b" in test data is rejected. averageDelay takes a readonly Departure[], promising callers it will not reorder or modify their array, and it accepts mutable arrays too, since anything you can do with a read-only array you can do with a mutable one. And the nested stop type is written inline, because nothing else needs it; if another type later needed it, you would lift it into its own interface Stop and refer to it by name.
Notice also what the types cannot do. If the service one day sends "delayMinutes": "4", a string, nothing here will notice, and addMinutes will concatenate rather than add. Describing a response is the first half of the job; checking that real responses match the description is the second, and lesson nine does it.
interface or type?
For describing an object shape, the two are almost interchangeable, and because typing is structural, an interface and an alias with the same shape are fully compatible:
// Declaration merging: two interface declarations with the same name combine.
// Libraries use this so that plugins can add fields to a shared type.
interface AppConfig {
appName: string;
}
// ...later, perhaps in a plugin's module:
interface AppConfig {
analytics?: { enabled: boolean };
}
const config: AppConfig = {
appName: "Harvest Tracker",
analytics: { enabled: false },
};
console.log(config.appName, config.analytics?.enabled);
// Interfaces and aliases are interchangeable for describing shapes,
// and structurally identical types are compatible, whatever their names.
interface PointI { x: number; y: number }
type PointT = { x: number; y: number };
const p1: PointI = { x: 1, y: 2 };
const p2: PointT = p1; // fine: same shape
console.log(p2.x + p2.y);
// Method syntax versus function-property syntax in object types.
interface Shape {
area(): number; // method signature
describe: () => string; // property holding a function
}
const square: Shape = {
area: () => 9,
describe() { return `a shape of area ${this.area()}`; },
};
console.log(square.describe());
export {};Harvest Tracker false
3
a shape of area 9The real differences:
interface | type alias | |
|---|---|---|
| Object shapes | yes | yes |
| Unions, tuples, primitives, function types, mapped and conditional types | no | yes |
| Extending | extends, which reports conflicts where they are written | &, which can silently produce never |
| Declaring the same name twice | the declarations merge | error: Duplicate identifier |
A class can implements it | yes | yes, if it is an object type |
Declaration merging is the one feature only interfaces have. Two interface AppConfig declarations combine into one with all the properties. Libraries rely on it to let you extend their types: you add a property to the browser's Window interface, or to a web framework's Request, by declaring an interface with the same name in the right scope. It is also a hazard: an interface whose name accidentally matches a global one merges with it silently.
The conventions you will meet in real code bases:
- "Interfaces for object shapes, type aliases for everything else." This was long the handbook's advice. Interfaces give clear names in error messages, can be extended with checked
extends, and are slightly cheaper for the compiler when large hierarchies are combined. - "Type aliases everywhere." Many teams use
typefor everything, for uniformity, and because it cannot merge by accident.
Both are fine. Pick one, write it down, and let a linter enforce it (typescript-eslint's consistent-type-definitions rule exists for exactly this). Never let the choice hold up a code review.
Method or function property?
In Shape, area(): number is a method signature and describe: () => string a property holding a function. They look like a matter of taste, and for calling they are. The difference is a deliberate gap in the type system: under --strict, parameters of function properties are checked strictly, while parameters of methods are checked more loosely (bivariantly, for compatibility with how the DOM's types were historically written). Some teams therefore prefer property syntax for callbacks in their own interfaces. You can ignore this until it bites; the rule's name, strictFunctionTypes, is what to search for when it does.
Modelling data well
A few habits make object types pay off:
- Model what is true, not what is convenient. If a user may genuinely have no email, write
email?: stringand let the compiler make every reader handle it. If every saved user has anidbut a new one doesn't yet, use two types (NewUserandUser) rather than one with an optionalidthat every function must check. - Keep types close to the code that owns them, and export them from the same module. Types describing an API's responses belong with the code that calls the API.
- Derive rather than repeat.
Note["text"]and, in lesson eight,Pick,OmitandPartiallet one type follow another, so that a change in one place propagates everywhere. - Mark what must not change as
readonly. It documents intent and catches accidental mutation, especially for data shared between parts of a program. - Prefer specific types to general ones.
status: "draft" | "published"beatsstatus: string;Record<"en" | "es", string>beatsRecord<string, string>when the keys are known.
Structural typing has one weakness for modelling: two types with the same shape are interchangeable, so a user ID and an order ID, both strings, can be mixed up without complaint. When that matters, teams use a branded type, an intersection with a property that never exists at run time:
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
const asUserId = (raw: string) => raw as UserId;
declare function cancelOrder(id: OrderId): void;
const user = asUserId("u-1029");
cancelOrder(user);main.ts(8,13): error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.
Type 'UserId' is not assignable to type '{ readonly __brand: "OrderId"; }'.
Types of property '__brand' are incompatible.
Type '"UserId"' is not assignable to type '"OrderId"'.At run time a UserId is just a string; the brand exists only for the checker. The single assertion lives in asUserId, ideally next to the code that validates the raw string, so every other function can demand the right kind of ID.
Common misconceptions
Misconception
"An object must match an interface exactly." It must have at least the required properties with compatible types; extra properties are fine, except in a fresh object literal, where TypeScript flags them as likely typos (lesson one).
Misconception
"readonly makes an object immutable." It prevents reassignment through that type, at compile time only. The same object can be changed through another reference whose type is not read-only, and nothing stops it at run time.
Misconception
"postcode?: string and postcode: string | undefined mean the same." The first allows the property to be absent; the second requires the property to be present, though its value may be undefined. With the option exactOptionalPropertyTypes (lesson nine), the first no longer even accepts an explicit undefined.
Misconception
"Record<string, number> means every key I look up will have a number." It means every key that exists has a number. Looking up a key that isn't there gives undefined at run time, while the type still claims number unless noUncheckedIndexedAccess is on. For lookups by keys that come from data, either turn that option on or use a Map, whose get honestly returns number | undefined.
Misconception
"Interfaces exist at run time, like in Java." Interfaces and aliases are erased completely. You cannot test x instanceof Person; to check a shape at run time you write a check of your own (lesson four) or use a validation library (lesson nine).
Exercises
Check type questions in the Playground by hovering, or by assigning to a variable of type never and reading the error.
1. Interfaces and type aliases
Warm-upComputationalWhat does this program print?
interface Box {
width: number;
height?: number;
}
const boxes: Box[] = [{ width: 2 }, { width: 3, height: 4 }];
console.log(boxes.map((b) => b.width * (b.height ?? 1)).join(","));
export {};
2. Interfaces and type aliases
CoreComputationalWith type ID = string | number; and type Note = { id: ID; text: string };, what type is Note["id"]? Write it in full, without using the name ID.
3. Interfaces and type aliases
CoreComputationalA file contains interface Settings { theme: string } and, further down, interface Settings { fontSize: number }. What happens with const s: Settings = { theme: "dark" };?
4. Interfaces and type aliases
CoreComputationalWhat is the type of the id property of { id: string } & { id: number }?
5. Interfaces and type aliases
CoreHumanWhich of these can be written only with a type alias, not with an interface? Choose all that apply.
6. Interfaces and type aliases
Warm-upComputationalWith interface Person { readonly id: number; name: string } and const p: Person = { id: 1, name: "Lin" };, which line is rejected?
7. Interfaces and type aliases
StretchComputationalIn the lesson's first program, amaka is an Employee, which extends Person (with an optional email). The program prints Object.keys(amaka).length. What number does it print?
Further reading and resources
- TypeScript Handbook: Object types · Microsoft
- TypeScript Handbook: Everyday types (differences between type aliases and interfaces) · Microsoft
- TypeScript Handbook: Indexed access types · Microsoft
- TypeScript Handbook: Type compatibility · MicrosoftThe precise rules of structural assignability.