我有这个界面:
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);
}
它说:
Class 'Point' declares interface 'IPoint' but does not implement it: Types of property 'getDist' of types 'Point' and 'IPoint' are incompatible:Call signatures of types '() => void' and '{ (): string; (x: number): any; }' are incompatible
执行此操作的正确方法是什么?
谢谢
最佳答案
当你在类中声明函数时,你需要用重载来装饰它:
getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
// your code
}
关于class - 接口(interface)和类中的函数重载 - 怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219289/