8

我有这个界面:

interface IPoint {
    getDist(): string;
    getDist(x: number): any;
}

我需要一个类来实现它,但我无法获得正确的语法来实现类中的 getDist() 方法。

class Point implements IPoint {
    // Constructor
    constructor (public x: number, public y: number) { }

    pointMethod() { }

    getDist() {
        Math.sqrt(this.x * this.x + this.y * this.y);
    }
    // Static member
    static origin = new Point(0, 0);
}

它说:

“Point”类声明了“IPoint”接口,但没有实现它:“Point”和“IPoint”类型的属性“getDist”类型不兼容:“() => void”和“{()”类型的调用签名:细绳; (x:数字):任何;}' 不兼容

这样做的正确方法是什么?

谢谢

4

4 回答 4

6

当你在类中声明函数时,你需要用重载来装饰它:

getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
    // your code
 }
于 2012-11-04T14:34:40.757 回答
5

这个答案描述了如何在 TypeScript 中实现方法重载,它并不漂亮:

interface IPoint {
    getDist(): string;
    getDist(x: number): any;
}

class Point implements IPoint {
    // Constructor
    constructor (public x: number, public y: number) { }

    pointMethod() { }

    getDist(x?: number) {
         if (x && typeof x == "number") {
             return 'foo';
         } else {
             return 'bar';
         }
    }
}

注意在接口中声明返回类型的特定组合,您只能从getDist.

于 2012-11-04T14:16:25.060 回答
1

你也可以使用默认值

interface Foo{
    next()
    next(steps: number)
    prev()
    prev(steps: number)
}

next(steps: number = 1) {
    // ...
}

prev(steps: number = 1) {
    // ...
}
于 2019-11-16T11:23:59.910 回答
0

以下是上述部分内容的变体

class Position {
    x: number;
    y: number;

    constructor(x : number = 0, y : number = 0) {
        this.x = x;
        this.y = y;
    }    
}

class Pen {
    colour: string;

    constructor(colour: string) {
        this.colour = colour;
    }
}

class PlottingHead {
    isPenUp: boolean;
    pen: Pen;
    position: Position;

    constructor() {     
       this.penUp();
   }

   move(p: Position): void;
   move(x: number, y: number): void;
   move(x: number | Position, y?: number): void {
        if (typeof x === "number")
        {
            x = new Position(x, y);
        }
        this.penUp();
        this.position = x;
    }

    draw(x: number | Position, y?: number): void {
        if (typeof x === "number")
        {
            x = new Position(x, y);
        }
        this.penDown();
        this.position = x;
    }

    penDown(): void {
        this.isPenUp = false;
     }

    penUp(): void {
        this.isPenUp = true;
    }

    onChangePen(newPen: Pen) {
        this.penUp();
        this.pen = newPen;
    }    
}

move函数采用单个位置对象或一对数值。这显然可以根据需要进行扩展。

于 2018-11-09T17:36:58.277 回答