Simonxca Simonxca - 1 year ago 139
TypeScript Question

Typescript method overloading in subclass

Here's an example:

class A {
func(): void {}

class B extends A {
func(a: number, b: string): void {}

Class B gives an error saying
is implemented incorrectly.

Ultimately, I'm trying to make this work:

var b: B;
b.func(0, ''); // func is overloaded by B
b.func(); // func is inherited from A

Is this currently possible in Typescript?

UPDATE: Fixed the code, accidentally used function properties instead of methods.

Answer Source

When using arrow functions you don't really get class methods but members of type/value of a function.
The difference being that while methods are added to the prototype, the arrow functions are added to the instance in the constrctor:

class MyClass {
    method() {}
    funct = () => {}

Compiles to:

var MyClass = (function () {
    function MyClass() {
        this.func = function () { };
    MyClass.prototype.method = function () { };
    return MyClass;

That's fine of course, if that's what you want.
The main problem with that is that overloading and calling the parent method aren't as simple.

In your case, with overloading:

class A {
    func(): void {}

class B extends A {
    func(): void; // parent signature
    func(a: number, b: string): void; // new signature
    func(): void {
        if (arguments.length === 0) {
        } else {
            // actual implementation
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download