Home > Back-end >  TypeScript Structural Typing with exception?
TypeScript Structural Typing with exception?

Time:12-16

I will provide two examples to show where I got stuck. In the first example I have two points: one 2d, one 3d:

type Point2D = { x: number, y: number };
type Point3D = { x: number, y: number, z: number };

let point2D: Point2D = { x: 10, y: 10 };
let point3D: Point3D = { x: 0, y: 0, z: 20 };

point2D = point3D; // without error.

While in another simple example on declaring/initializing a point(2d) it shows an error:

type Point = { x: number, y: number };
let point: Point = { x: 0, y: 0, yy: 0 }; // Error

The error:

Type '{ x: number; y: number; yy: number; }' is not assignable to type 'Point'.
  Object literal may only specify known properties, and 'yy' does not exist in type 'Point'.

Can anyone teach me why the behaviour is different?

Here is my trying explanation. I'm new to TS so this is absolutely not a formal one:

In the first example, the entire init object is expected to be used(by intuition). While in the second example, it's an assignment and it's normal to expect that something surplus will be dropped in an assignment.

CodePudding user response:

The reason why point2d = point3d statement does not throw error is:

TypeScript Excess Property Checks

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.

TypeScript lets us pass { size: number; label: string; } to something that only expected a { label: string; }

For the below example:

type Point = { x: number, y: number };
let point: Point = { x: 0, y: 0, yy: 0 }; 

This code throws an error because the object literal has a property yy that the target type Point doesn't have.

  • Related