typescript1.7 - Typescript: Pass an extra parameter -
i trying below code 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" }); // fields ok getx({ x: 0 }); // error: supplied parameter not match
as per code comment says below line should ok.
getx({ x: 0, y: 0, color: "red" }); // fields ok
but getting error below:
error ts2345: argument of type '{ x: number; y: number; color: string; }' not assignable parameter of type 'point'. object literal may specify known properties, , 'color' not exist in type 'point'
but below code works re-wrote in made params 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" }); // fields ok getx({ x: 0 }); // error: supplied parameter not match
please can me out if documentation wrong or missing here
fyi using:
- typescript v1.7.5
- visual studio code
screenshot:
the documentation out of date. used ok add property, in typescript 1.6 changed behaviour.
if want work in ts 1.6+ have type assertion:
getx({ x: 0, y: 0, color: "red" } point); // no error
Comments
Post a Comment