Method overriding lets a child class change how a method works from its parent class. Using types helps keep the code safe and clear.
0
0
Method overriding with types in Typescript
Introduction
You want a child class to do something different when a method is called.
You need to keep the same method name but change its behavior.
You want TypeScript to check that your new method matches expected types.
You want to add extra features in the child class method while keeping the parent method's contract.
Syntax
Typescript
class Parent { methodName(param: Type): ReturnType { // parent method code } } class Child extends Parent { methodName(param: Type): ReturnType { // child method code } }
The child method must have the same name as the parent method.
TypeScript checks that the parameter and return types match or are compatible.
Examples
The
Dog class changes how speak works but keeps the same types.Typescript
class Animal { speak(sound: string): string { return `Animal says: ${sound}`; } } class Dog extends Animal { speak(sound: string): string { return `Dog barks: ${sound}`; } }
The child class
AdvancedCalculator overrides calculate to multiply instead of add.Typescript
class Calculator { calculate(x: number, y: number): number { return x + y; } } class AdvancedCalculator extends Calculator { calculate(x: number, y: number): number { return x * y; } }
Sample Program
This program shows a parent class Vehicle with a method move. The child class Car overrides move to give a different message. Both methods use the same parameter and return types.
Typescript
class Vehicle { move(distance: number): string { return `Vehicle moved ${distance} meters.`; } } class Car extends Vehicle { move(distance: number): string { return `Car drove ${distance} meters.`; } } const myVehicle = new Vehicle(); const myCar = new Car(); console.log(myVehicle.move(10)); console.log(myCar.move(10));
OutputSuccess
Important Notes
Overriding methods must keep compatible types to avoid TypeScript errors.
You can call the parent method inside the child method using super.methodName() if needed.
Summary
Method overriding lets child classes change parent methods.
TypeScript ensures the method types stay compatible.
This helps write clear and safe code with flexible behavior.