Skip to content

Typescript: Pass an extra parameter #6963

Closed
@nirus

Description

@nirus

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:

I have attached the screenshot FYI.
capture

Metadata

Metadata

Assignees

Labels

SpecIssues related to the TypeScript language specification

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions