Functions Overloading in the interface and classes - how?

I have this interface:

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

and I need a class to implement it, but I can’t get the correct syntax to implement the getDist () method in the class.

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);
}

He says:

The Point class declares the IPoint interface, but does not implement it: The 'getDist' property types of the 'Point' and 'IPoint' types are incompatible: call signatures of the types' () => void 'and' {(): string; (x: number): any; } 'incompatible

What is the right way to do this?

thank

+1
source share
2 answers

When you declare a function in a class, you need to decorate it with overloads:

getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
    // your code
 }
+3
source

, 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';
         }
    }
}

N.B. , getDist.

+2

All Articles