Nirus February 2016

Typescript: Pass an extra parameter

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

Screenshot:

Answers


David Sherret February 2016

The documentation is out of date. It used to be ok to add an extra property, but in TypeScript 1.6 they changed the behaviour.

If you want this to work in TS 1.6+ then you have to do a type assertion:

getX({ x: 0, y: 0, color: "red" } as Point); // no error

Post Status

Asked in February 2016
Viewed 2,766 times
Voted 7
Answered 1 times

Search




Leave an answer