TypeScript uses structural typing, as such two types are compatible if their members are compatible:
class Point2D {
x: number = 1
y: number = 2
}
class Point3D {
x: number = 1
y: number = 2
z: number = 3
}
function iTake2D(p:Point2D) { /* do something */ }
const threeD:Point3D = new Point3D()
iTake2D(threeD) // okay
iTake2D(new Point3D()) // okay
However, in the example bellow structural type checking seems to fail:
interface Point2D {
x: number
y: number
}
interface Point3D {
x: number
y: number
z: number
}
function iTake2D(p:Point2D) { /* do something */ }
const threeD:Point3D = { x: 1, y: 3, z: 1 }
iTake2D(threeD) // okay
iTake2D({ x: 1, y: 3, z: 1 }) // Not okay!
// ^^^^
// [tsserver 2345] [E] Argument of type '{ x: number; y: number; z: number; }'
// is not assignable to parameter of type 'Point2D'.
// Object literal may only specify known properties, and 'z' does not exist in
// type 'Point2D'.
What am I missing? Please help!
Here are the Typescript playground links to the above two examples: (link-to-eg-1), (link-to-eg-2)