Excess Properties When Casting In TypeScript

TopicSource
๐Ÿฆ’ TypeScriptTypeScript course by the native web

When casting an object into an interface that has fewer properties than the object, this actually works, but you lose the property to access those properties, even though they are still saved inside the object.

interface Point2D {
  x: number;
  y: number;
}

interface Point3D {
  x: number;
  y: number;
  z: number;
}

const firstPoint: Point3D = {
  x: 42,
  y: 23,
  z: 17
};

const secondPoint: Point2D = firstPoint; // this is valid

console.log(secondPoint);
// output: { x: 12, y: 23, z: 17 }

To access those properties, you have to cast the object into the other interface again:

console.log((secondPoint as Point3D).z);

  1. Interfaces in TypeScript