Bas*_*adi 6 overloading interface class typescript
我有这个界面:
interface IPoint {
getDist(): string;
getDist(x: number): any;
}
Run Code Online (Sandbox Code Playgroud)
我需要一个类来实现它,但我无法获得正确的语法来实现该类中的 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);
}
Run Code Online (Sandbox Code Playgroud)
它说:
“Point”类声明了接口“IPoint”,但没有实现它:“Point”和“IPoint”类型的属性“getDist”类型不兼容:“() => void”和“{()”类型的调用签名:细绳; (x: 数字): 任何; }' 不兼容
这样做的正确方法是什么?
谢谢
当你在类中声明函数时,你需要用重载来装饰它:
getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
// your code
}
Run Code Online (Sandbox Code Playgroud)
这个答案描述了如何在 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';
}
}
}
Run Code Online (Sandbox Code Playgroud)
NB 使用接口中声明的返回类型的特定组合,您只能从getDist.
| 归档时间: |
|
| 查看次数: |
12710 次 |
| 最近记录: |