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.
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.
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.
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With