TYPESCRIPT
TypeScript Inheritance: Syntax, Usage, and Examples
TypeScript inheritance allows one class to extend another, enabling code reuse and a structured approach to object-oriented programming. With inheritance, you can define a base class and extend it to create new classes with additional or modified behavior.
How to Use Inheritance in TypeScript
To create a class that inherits from another, use the extends
keyword. The subclass gains access to the parent class's properties and methods.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log("Some generic sound");
}
}
class Dog extends Animal {
bark(): void {
console.log("Woof!");
}
}
const myDog = new Dog("Buddy");
console.log(myDog.name); // Output: Buddy
myDog.makeSound(); // Output: Some generic sound
myDog.bark(); // Output: Woof!
- The
Animal
class serves as the base class. - The
Dog
class extendsAnimal
, inheriting thename
property andmakeSound
method while adding its own method,bark()
.
When to Use Inheritance in TypeScript
Avoiding Code Duplication
Inheritance lets you define shared behavior in a base class and extend it where needed. This prevents code duplication and improves maintainability.
class Employee {
constructor(public name: string, public role: string) {}
work(): void {
console.log(`${this.name} is working as a ${this.role}.`);
}
}
class Manager extends Employee {
scheduleMeeting(): void {
console.log(`${this.name} is scheduling a meeting.`);
}
}
const manager = new Manager("Alice", "Manager");
manager.work(); // Output: Alice is working as a Manager.
manager.scheduleMeeting(); // Output: Alice is scheduling a meeting.
Building Class Hierarchies
You can create hierarchies where a base class defines general behavior, and subclasses refine it.
class Vehicle {
move(): void {
console.log("Vehicle is moving.");
}
}
class Car extends Vehicle {
drive(): void {
console.log("Car is driving.");
}
}
class Bicycle extends Vehicle {
pedal(): void {
console.log("Bicycle is pedaling.");
}
}
const bike = new Bicycle();
bike.move(); // Output: Vehicle is moving.
bike.pedal(); // Output: Bicycle is pedaling.
Overriding Methods
You can redefine inherited methods in a subclass using method overriding.
class Bird {
fly(): void {
console.log("This bird is flying.");
}
}
class Penguin extends Bird {
fly(): void {
console.log("Penguins cannot fly.");
}
}
const penguin = new Penguin();
penguin.fly(); // Output: Penguins cannot fly.
Examples of Inheritance in TypeScript
Inheriting Constructors
When a subclass has its own constructor, it must call super()
to invoke the parent’s constructor.
class Person {
constructor(public name: string, public age: number) {}
}
class Student extends Person {
constructor(name: string, age: number, public grade: number) {
super(name, age);
}
introduce(): void {
console.log(`Hi, I'm ${this.name}, I'm ${this.age}, and I'm in grade ${this.grade}.`);
}
}
const student = new Student("Leo", 16, 10);
student.introduce(); // Output: Hi, I'm Leo, I'm 16, and I'm in grade 10.
Using super
to Call Parent Methods
Subclasses can call methods from the parent class using super
.
class Parent {
greet(): void {
console.log("Hello from the parent class.");
}
}
class Child extends Parent {
greet(): void {
super.greet();
console.log("Hello from the child class.");
}
}
const child = new Child();
child.greet();
// Output:
// Hello from the parent class.
// Hello from the child class.
Interface Inheritance
An interface can extend another interface, allowing composition of multiple types.
interface Named {
name: string;
}
interface Employee extends Named {
jobTitle: string;
}
const worker: Employee = {
name: "John",
jobTitle: "Developer",
};
console.log(worker.name); // Output: John
console.log(worker.jobTitle); // Output: Developer
Learn More About Inheritance in TypeScript
Multiple Inheritance Workarounds
TypeScript does not support multiple inheritance (a class cannot extend more than one class), but you can use mixins to achieve similar functionality.
class Walker {
walk(): void {
console.log("Walking...");
}
}
class Swimmer {
swim(): void {
console.log("Swimming...");
}
}
class Athlete implements Walker, Swimmer {
walk!: () => void;
swim!: () => void;
}
Object.assign(Athlete.prototype, Walker.prototype, Swimmer.prototype);
const athlete = new Athlete();
athlete.walk(); // Output: Walking...
athlete.swim(); // Output: Swimming...
Class vs. Interface Inheritance
A class inheritance relationship (extends
) means that the subclass gets both structure and behavior. An interface inheritance relationship (implements
) only provides structure.
interface Flyable {
fly(): void;
}
class Airplane implements Flyable {
fly(): void {
console.log("The airplane is flying.");
}
}
const plane = new Airplane();
plane.fly(); // Output: The airplane is flying.
Generic Inheritance
You can use generics in inheritance to create reusable base classes.
class Box<T> {
constructor(public value: T) {}
getValue(): T {
return this.value;
}
}
class NumberBox extends Box<number> {}
const numBox = new NumberBox(42);
console.log(numBox.getValue()); // Output: 42
Composition vs. Inheritance
In some cases, composition (using object properties rather than inheritance) is a better choice than extending classes.
class Engine {
start(): void {
console.log("Engine started.");
}
}
class Car {
engine: Engine;
constructor() {
this.engine = new Engine();
}
start(): void {
this.engine.start();
console.log("Car started.");
}
}
const myCar = new Car();
myCar.start();
// Output:
// Engine started.
// Car started.
Object Inheritance
Objects in TypeScript can inherit properties from other objects using Object.create()
.
const person = {
greet: function () {
console.log("Hello!");
},
};
const employee = Object.create(person);
employee.greet(); // Output: Hello!
TypeScript inheritance helps organize code by defining base classes and extending them for specialization. It allows code reuse, method overriding, and structured object-oriented programming.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.