Welcome back! I am Mihir, and in this lesson we will learn abstract classes in TypeScript.
An abstract class is a base class that cannot be created directly. It is meant to be extended by other classes.
Basic Abstract Class
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}makeSound is abstract, so child classes must implement it.
move is a normal method and can be reused.
Extending an Abstract Class
class Dog extends Animal {
makeSound(): void {
console.log("Woof");
}
}
const dog = new Dog();
dog.makeSound();
dog.move();Dog must implement makeSound.
You Cannot Instantiate Abstract Classes
Invalid:
const animal = new Animal();Abstract classes are only for inheritance.
Abstract Methods
Abstract methods have no body.
abstract class PaymentProcessor {
abstract pay(amount: number): void;
}Child classes provide the actual behavior.
class StripeProcessor extends PaymentProcessor {
pay(amount: number): void {
console.log(`Paid ${amount} with Stripe`);
}
}Abstract Properties
You can also require properties.
abstract class Shape {
abstract name: string;
abstract getArea(): number;
}
class Square extends Shape {
name = "square";
constructor(public size: number) {
super();
}
getArea(): number {
return this.size * this.size;
}
}Abstract Class vs Interface
Use an interface when you only need a contract.
Use an abstract class when you need a contract plus shared implementation.
abstract class BaseService {
protected log(message: string) {
console.log(`[Service] ${message}`);
}
abstract run(): void;
}Child classes get the shared log method.
Quick Recap
- Abstract classes cannot be instantiated directly.
- They are meant to be extended.
- Abstract methods and properties must be implemented by child classes.
- Abstract classes can include shared concrete methods.
- Use them when subclasses need common behavior.
Next up, we will learn Static Members →.