Structural typing checks if things look alike to decide if they match. Nominal typing checks if things have the same name or label to decide if they match.
How structural typing differs from nominal typing in Typescript
// Structural typing example interface Point { x: number; y: number; } function printPoint(p: Point) { console.log(p.x, p.y); } // Nominal typing example (using classes) class User { constructor(public name: string) {} } class Admin { constructor(public name: string) {} } let user: User = new User('Alice'); let admin: Admin = new Admin('Bob');
Structural typing compares the shape (properties and types) of objects.
Nominal typing compares the explicit names or declarations of types or classes.
interface Point { x: number; y: number; }
function logPoint(p: Point) {
console.log(`x: ${p.x}, y: ${p.y}`);
}
const pointLike = { x: 10, y: 20, z: 30 };
logPoint(pointLike);class User { constructor(public name: string) {} } class Admin { constructor(public name: string) {} } let user: User = new User('Alice'); let admin: Admin = user; // Error in TypeScript (nominal typing for classes)
This program shows how structural typing allows objects with extra properties to be used where a smaller shape is expected. It also contrasts with nominal typing, where the class assignment would fail despite matching shapes (and in TypeScript it does fail).
interface Point { x: number; y: number; }
function printPoint(p: Point) {
console.log(`x: ${p.x}, y: ${p.y}`);
}
const point = { x: 5, y: 10 };
const point3D = { x: 5, y: 10, z: 15 };
printPoint(point); // Works
printPoint(point3D); // Works because of structural typing
class User { constructor(public name: string) {} }
class Admin { constructor(public name: string) {} }
const user = new User('Alice');
const admin = new Admin('Bob');
// The following line errors in TypeScript:
// let admin2: Admin = user; // Error: nominal typing for classesStructural typing is like matching puzzle pieces by shape, ignoring the picture on them.
Nominal typing is like matching puzzle pieces only if they come from the same box (name).
TypeScript uses structural typing for interfaces and types, but classes behave more like nominal types.
Structural typing checks if objects have the same shape (properties and types).
Nominal typing checks if types have the same explicit name or declaration.
TypeScript mainly uses structural typing, but classes add some nominal typing behavior.