Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 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 any errors.
In another straightforward example of declaring/initializing a 2d point, an error is thrown:
type Point = { x: number, y: number };
let point: Point = { x: 0, y: 0, yy: 0 }; // Error
The error message reads as follows:
Type '{ x: number; y: number; yy: number; }' is not compatible with type 'Point'.
An object literal can only specify existing properties, and 'yy' does not exist within the type 'Point'.
I am curious to understand why this discrepancy in behavior occurs. Can someone enlighten me on this matter?
Here is my attempt at providing an explanation. Please note that I am new to TypeScript, so this is purely based on my observations:
In the first example, it seems logical to expect the entire initialization object to be utilized. On the other hand, in the second example, it involves an assignment where any extra information is typically disregarded.