Mike Lischke
Mike Lischke

Reputation: 53417

Method overloading in descendent classes in Typescript

What I have in mind is pretty simple:

class A {
    getSomething(name: string): number {
        return 1;
    }

 }

class B extends A {
    getSomething(n: number, name: string): number {
        return 2;
    }
}

A method defined in one class should get overloaded with an additional parameter in a descendent class. In reality the method in class B will detour to A depending on the new parameter. However, I get the error:

Class 'B' incorrectly extends base class 'A'. Types of property 'getSomething' are incompatible. Type '(n: number, name: string) => number' is not assignable to type '(name: string) => number'.

See this code in playground. What would be the correct approach here? Is this possible at all?

Upvotes: 2

Views: 823

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29926

You could explicitly declare the overloaded function signatures:

class A {
    getSomething(name: string): number {
        return 1;
    }

 }

class B extends A {
    getSomething(name: string): number;
    getSomething(n: number, name: string): number;

    getSomething(n, name?) {
        return 2;
    }
}

EDIT

With the above you override the original function too. It is your responsibility to call the superclasses function when the parameters are given that way. An example:

class A {
    getSomething(name: string): number {
        return 1;
    }
 }

class B extends A {
    getSomething(name: string): number;
    getSomething(n: number, name: string): number;

    getSomething(n: any, name?: any): any {
        if (typeof name !== "string") { 
            return super.getSomething(n);
        } 
        return 2;
    }
}

Upvotes: 3

Related Questions