5 min read
•Question 47 of 48hardHow does Type Compatibility work in TypeScript?
Structural vs nominal typing.
What You'll Learn
- Structural typing
- Duck typing principle
- Excess property checks
Structural Typing
TypeScript uses structural typing - types are compatible if they have the same shape.
code.tsTypeScript
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(p.x, p.y);
}
// Works! Has x and y
const point3D = { x: 1, y: 2, z: 3 };
logPoint(point3D);Duck Typing
"If it walks like a duck and quacks like a duck..."
code.tsTypeScript
class Bird {
fly() { console.log("Flying"); }
}
class Airplane {
fly() { console.log("Flying"); }
}
function makeItFly(thing: { fly(): void }) {
thing.fly();
}
makeItFly(new Bird()); // OK
makeItFly(new Airplane()); // OKExcess Property Checks
Direct object literals are checked more strictly.
code.tsTypeScript
interface User {
name: string;
}
// Error: Object literal has extra property
const user: User = {
name: "John",
age: 30 // Error!
};
// But this works
const data = { name: "John", age: 30 };
const user2: User = data; // OKNominal-like Typing
code.tsTypeScript
// Brand types for nominal behavior
type USD = number & { __brand: "USD" };
type EUR = number & { __brand: "EUR" };
function payUSD(amount: USD) { }
const euros = 100 as EUR;
payUSD(euros); // Error!