Sub topic 1
Structural vs nominal typing
Prerequisites
Assume you know basic TypeScript type annotations, interfaces, type aliases, JavaScript objects, classes, and functions.
Structural vs nominal typing
A type system is structural when it compares values by their members. A type system is nominal when it compares declared type names.
TypeScript uses structural typing. If an object has the required properties with compatible types, TypeScript usually accepts it, even when the object came from a different interface or class.
interface Point {
x: number;
y: number;
}
function logPoint(point: Point): void {
console.log(`${point.x}, ${point.y}`);
}
const point3d = { x: 1, y: 2, z: 3 };
logPoint(point3d); // OK: x and y have the required typesThe Point interface does not need to declare that point3d implements it. The extra z property does not prevent assignment.
Assignability: does the shape fit?
Assignability means that a value of one type can be used where another type is expected. For object types, compare the target's required members with the source's members.
The source must provide every required property. Each property must have a compatible type. Additional properties are normally allowed when the source is a variable.
interface Named {
name: string;
}
const user = {
name: "Mina",
active: true,
};
const named: Named = user; // OKThe target type asks only for name, so user fits its required shape.
Object shapes and extra properties
TypeScript performs an excess property check for a fresh object literal. This catches likely spelling mistakes:
interface Options {
color?: string;
width?: number;
}
const options: Options = {
colour: "red",
};
// Error: "colour" is not a known propertyThe same extra property can pass through a variable because structural assignability checks whether the required shape exists:
const supplied = { color: "red", height: 20 };
const options: Options = supplied; // OKExercise
Is { x: 1, y: 2, z: 3 } structurally assignable to { x: number; y: number } through a variable?
Show answer
Yes. It contains all required properties with compatible types.