1.4 Structural Subtyping

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.

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. function getX(p: Point) {
  6. return p.x;
  7. }
  8. class CPoint {
  9. x: number;
  10. y: number;
  11. constructor(x: number, y: number) {
  12. this.x = x;
  13. this.y = y;
  14. }
  15. }
  16. getX(new CPoint(0, 0)); // Ok, fields match
  17. getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
  18. getX({ x: 0 }); // Error: supplied parameter does not match

See section 3.11 for more information about type comparisons.