Object literals in Typescript

in Front-End Web Technologies

Consider the following code written in Typescript

  interface Point {
      x: number;
      y: number;
  }
  
  function dump(pt: Point) {
      console.log(pt.x + ", " + pt.y);
  }
  
 dump({x: 10, y:20, z: 30});

The Typescript compiler raises the following error:

Argument of type ‘{ x: number; y: number; z: number; }’ is not assignable to parameter of type ‘Point’.
Object literal may only specify known properties, and ‘z’ does not exist in type ‘Point’

Now, consider the following fix

  interface Point {
      x: number;
      y: number;
  }
  
  function dump(pt: Point) {
      console.log(pt.x + ", " + pt.y);
  }
  
 let obj = {x: 10, y:20, z: 30}; 
 dump(obj);

This time, no error is reported. It seems as the Typescript compiler treats object literal different than plain JavaScript object

The formal name for this kind of behavior is known as “excess property checking”. Here is the quote from the Typescript documentation:

“Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error”

Enjoy,

Contact us
You might also like
Share: