class - 接口(interface)和类中的函数重载 - 怎么做?

标签 class interface overloading typescript

我有这个界面:

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/

相关文章:

c++ - 标识哪个类提供由重载决策选择的函数的类型特征

java - 重载库类构造函数

java - 需要为用户生成每个学生的卷号吗?

c++ - 从具有不同子类的父指针调用子方法

go - go 支持多类型吗? (泛型类型)

c++ - 从指针转换为非标量对象类型?

javascript - 更好的方法来处理 JavaScript 类中的状态变化

java - 在数组中存储变量?

c# - 如果 <T> 是动态的,我如何测试 Enumerable<T> 中的 <T> 是否实现了接口(interface)?

c# - 结构体实现接口(interface)是否安全?