Object types are compared structurally. For example, in the code fragment below, class 'CPoint' matches interface 'Point' because 'CPoint' has all of the required members of 'Point'. A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility. The example also illustrates that an object type can match the type inferred from an object literal, as long as the object literal supplies all of the required members.
interface Point {
x: number;
y: number; }
function getX(p: Point) {
return p.x; }
class CPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
} }
getX(new CPoint(0, 0)); // Ok, fields match
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not match
In their example CPoint is considered of type Point, since it is of type Point I can pass it anywhere I can a Point. If Point stated that all implementors had method Foo(x:string), CPoint wouldn't have that method. Thus anyone accepting a Point and expecting to use Foo would blow up if CPoint was passed into it.
My question is, am I interpreting this wrong, if not why is this considered a good enough to put into the language specs?