Closed
Description
I was trying the below code from the documentation
interface Point {
x: number;
y: number;
}
function getX(p: Point) {
return p.x;
}
class CPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
getX(new CPoint(0, 0)); // Ok, fields match
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not match
As per the code comment says below line should be ok.
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
But i am getting error as below:
error TS2345: Argument of type '{ x: number; y: number; color: string; }' is not assignable to parameter of type 'Point'. Object literal may only specify known properties, and 'color' does not exist in type 'Point'
But the below code works well which i re-wrote in which i made params as optional:
interface Point {
x: number;
y?: number;
color?: string;
}
function getX(p: Point) {
return p.x;
}
class CPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
getX(new CPoint(0, 0)); // Ok, fields match
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not match
Please can somebody help me out if the documentation is wrong or am i missing something here
FYI i am using:
- Typescript v1.7.5
- Visual studio code
Same is been asked in stackoverflow: