Sub topic 3
Structural Typing: Shape, Not Name
Prerequisites and the core idea
This chapter assumes basic TypeScript syntax, interfaces, type aliases, functions, and arrays. It also assumes you have seen compiler errors such as “is not assignable to.”
TypeScript uses structural typing. A type is compatible with another type when its structure contains everything the target requires. TypeScript usually does not require the source and target to have the same declared name.
Think of an object type as a list of requirements. If a value provides those requirements with compatible types, the assignment succeeds.
interface Point {
x: number;
y: number;
}
const point3d = { x: 1, y: 2, z: 3 };
const point: Point = point3d;
console.log(point.x, point.y);point3d has x and y, so it can be used as a Point. Its additional z property does not prevent the assignment.
Required and optional properties
The target type controls which properties must exist. An optional property may be absent, but a required property cannot be missing.
interface User {
id: number;
name?: string;
}
const first: User = { id: 1 };
const second: User = { id: 2, name: "Mina" };
// @ts-expect-error: id is required
const invalid: User = { name: "Mina" };Property types must also be compatible. A string cannot satisfy a number requirement.
A readonly property prevents writes through that particular type. It does not make the entire object immutable, and it usually does not block assignment from an object with a mutable property.
Fresh object literals and excess properties
TypeScript applies an additional check to a fresh object literal written directly in an assignment. This is called an excess property check.
interface Point {
x: number;
y: number;
}
const saved = { x: 1, y: 2, z: 3 };
const okay: Point = saved;
// @ts-expect-error: fresh literals reject unknown properties
const rejected: Point = { x: 1, y: 2, z: 3 };This check catches likely spelling mistakes. It does not change the general structural rule. Assigning through a variable first allows the extra property because the variable already has a known type.
Reading an assignment
When an assignment fails, identify the source on the right and the target on the left. Then check every target requirement against the source.
Classes can also participate in structural typing, but private or protected members must originate from the same class declaration. That rule prevents unrelated classes with identical public methods from being treated as interchangeable.
Exercise
Why does const p: Point = { x: 1, y: 2, z: 3 } trigger an error while assigning the same object through a variable can succeed?
Show answer
The direct object is a fresh literal, so TypeScript performs an excess property check. The variable assignment uses its existing structural type.