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.
Practice
structural typing in TypeScript?Solution
Step 1: Understand structural typing concept
Structural typing means compatibility depends on the shape (properties and types) of objects, not their names.Step 2: Compare with nominal typing
Nominal typing requires exact type names or declarations to match, which is not how TypeScript works by default.Final Answer:
Types are compatible if their properties and types match, regardless of their names. -> Option AQuick Check:
Structural typing = shape-based compatibility [OK]
- Confusing structural typing with nominal typing
- Thinking type names must match for compatibility
- Assuming runtime checks for type compatibility
Solution
Step 1: Check property shapes for compatibility
const a: {name: string} = {name: 'Alice'}; const b: {name: string} = a; assigns an object with a matching propertyname: stringto another variable with the same shape, which is allowed.Step 2: Analyze other options for incompatibility
A mismatches properties (id vs name), B uses classes (nominal typing), D mismatches property types.Final Answer:
const a: {name: string} = {name: 'Alice'}; const b: {name: string} = a; -> Option AQuick Check:
Matching shapes = compatible [OK]
- Assuming different property names are compatible
- Ignoring property type mismatches
- Confusing class inheritance with structural typing
interface Point { x: number; y: number; }
interface Named { name: string; }
const p: Point = { x: 10, y: 20 };
const n: Named = { name: 'Origin' };
function printPoint(point: Point) {
console.log(`x=${point.x}, y=${point.y}`);
}
printPoint(p);
printPoint(n as unknown as Point);Solution
Step 1: Understand structural typing and casting
The objectpmatchesPointshape, soprintPoint(p)prints x=10, y=20. The objectndoes not havexory, but is forced cast toPoint.Step 2: Predict output for forced cast
At runtime,nlacksxandy, so accessing them printsundefined.Final Answer:
x=10, y=20 x=undefined, y=undefined -> Option BQuick Check:
Forced cast ignores shape, runtime undefined properties [OK]
- Expecting runtime type errors
- Assuming cast adds missing properties
- Confusing property names with values
interface A { id: number; }
interface B { id: number; name: string; }
const a: A = { id: 1 };
const b: B = a;Solution
Step 1: Check property requirements for assignment
Variablebexpects an object withidandname. Variableaonly hasid.Step 2: Understand structural typing rules
Structural typing requires the assigned object to have at least the required properties. Here,ais missingname, so assignment fails.Final Answer:
Error becausealacks propertynamerequired byB. -> Option DQuick Check:
Missing required properties cause assignment error [OK]
- Ignoring missing properties in assignment
- Thinking interface names must match for compatibility
- Assuming partial property match is enough
class Person { name: string; constructor(name: string) { this.name = name; } }
class Employee { name: string; salary: number; constructor(name: string, salary: number) { this.name = name; this.salary = salary; } }
let p: Person = new Person('Alice');
let e: Employee = new Employee('Bob', 50000);
// Which assignment is valid?
// 1) p = e;
// 2) e = p;Solution
Step 1: Compare properties of Person and Employee
Person hasname. Employee hasnameandsalary. Employee has all Person properties plus more.Step 2: Apply structural typing rules for assignment
Assigninge(Employee) top(Person) is allowed becauseehas at least the properties ofp. The reverse is not allowed becauseplackssalary.Final Answer:
Only assignment 1) p = e; is allowed because Employee has all Person properties. -> Option CQuick Check:
Subtype with extra properties can assign to supertype [OK]
- Assuming both assignments are allowed
- Confusing nominal typing with structural typing here
- Ignoring extra properties in assignment compatibility
Ready to prove it?
Pass the test and this pattern moves unknown
