One of the key principles of TypeScript is that type checking focuses on the structure of values, a concept known as duck typing or structural typing. This means that only a subset of an object's fields needs to match for it to be considered compatible.
For instance, in TypeScript, the following code is valid:
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
const rect = { x: 33, y: 3, width: 30, height: 80 };
logPoint(rect); // logs "33, 3"
However, if you directly call the logPoint function with an object literal, TypeScript will raise a warning:
logPoint({ x: 33, y: 3, width: 30, height: 80 }); // error
So, why does subset type-matching work in the first case but not in the second?
Links: