打字稿:传递一个额外的参数

Typescript: Pass an extra parameter

我正在尝试 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

根据代码注释,下面一行应该没问题。

getX({ x: 0, y: 0, color: "red" });  // Extra fields Ok

但是我收到如下错误:

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'

但下面的代码运行良好,我重新编写了其中我将参数设置为可选的代码:

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

如果文档有误或者我遗漏了什么,请有人帮助我

仅供参考,我正在使用:

截图:

文档已过时。过去可以添加额外的 属性,但在 TypeScript 1.6 中它们 changed the behaviour.

如果你想让它在 TS 1.6+ 中工作,那么你必须做一个类型断言:

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