Typescript overloading a function of a child class

How can I achieve something similar to this pattern in typescript?

class A {
    Init(param1: number) {
        // some code
    }
}

class B extends A {
    Init(param1: number, param2: string) {
        // some more code
    }
}

The code cut above looks as if it should work, but with a closed inspection of How the Typescript function overload function works , an error occurs:

TS2415: 'Class 'B' incorrectly extends base class 'A'. 
Types of property 'Init' are incompatible.

I know that constructor functions allow this behavior, but I cannot use constructors here because these objects are combined for memory efficiency.

I could provide another definition of Init () in class A:

class A {
    Init(param1: number, param2: string): void;
    Init(param1: number) {
        // some code
    }
}

However, this is not as ideal as the base class should now know about all its derived classes.

Init B, , Init() , , Init() .

, ?

+4
1

TypeScript , : , ?

let a:A = new A(); // a is of type A
a.Init(1)
a = new B(); // a is still of type A, even if it contains B inside
a.Init(1) // second parameter is missing for B, but totally valid for A, will it explode?

, , B, A:

class B extends A {
    Init(param1: number, param2?: string) { // param 2 is optional
        // some more code
    }
}

, :

class C extends A {
    Init(param1: string) { // param 1 is now string instead of number
        // some more code
    }
}

, .

class C extends A {
    Init(param1: number)
    Init(param1: string)
    Init(param1: number | string) { // param 1 is now of type number | string (you can also use <any>)
        if (typeof param1 === "string") { // param 1 is now guaranteed to be string
            // some more code
        }
    }
}

, A . , .

+3

All Articles