Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter method signature for child class in Typescript?

In the example below (Typescript, 1.7+), what would I have to change to allow B.callback to have a different signature than A.callback?

class A {
    callback(result: number) {
    }
}


class B extends A {
    callback(result: number, option: number) {
    }
}

Currently this gives test.ts(7,7): error TS2415: Class 'B' incorrectly extends base class 'A'.

In the real world my example is more complex, but I can dynamically (more or less) guarantee (based on some configuration) that the requested parameters will be there.

like image 717
left4bread Avatar asked Nov 05 '15 10:11

left4bread


People also ask

How do I override a TypeScript method?

To override a class method in TypeScript, extend from the parent class and define a method with the same name. Note that the types of the parameters and the return type of the method have to be compatible with the parent's implementation. Copied! class Parent { doMath(a: number, b: number): number { console.

How do you write a function inside a class in TypeScript?

Functions are general building blocks inside a class that hold some business logic. Creating a function in TypeScript is similar to the process in JavaScript: You use the function keyword. However, in TypeScript you also have the option to define the type of parameters and return type of the function.

How do you call the base class constructor from the child class in TypeScript?

You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.

Does TypeScript have inheritance?

TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript.


1 Answers

Depending on the situation, the following solution may suffice too:

class A {
    callback(result: number) {
    }
}


class B extends A {
    callback(result: number, option?: number) { // make 'option' optional
    }
}
like image 154
Martin Vseticka Avatar answered Sep 27 '22 15:09

Martin Vseticka