Skip to main content

Abstract Classes & Interfaces in TypeScript (Live Playground)

In this tutorial, we will explore abstract classes and interfaces in TypeScript, which are essential components of advanced object-oriented programming (OOP).

Abstract Classes​

Abstract classes are base classes that cannot be instantiated. They are used to define a common structure and behavior for derived classes. Abstract classes can have abstract methods, which must be implemented in the derived classes.

TypeScript
abstract class Animal {
constructor(public name: string) {}

abstract speak(): void;
}

class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Max');
dog.speak(); // Max barks.
Live Playground, Try it Yourself

Interfaces​

Interfaces are used to define the structure of an object, like a contract that must be followed by any class implementing the interface. Interfaces can also be used to define the structure of function types.

TypeScript
interface Animal {
name: string;
speak(): void;
}

class Dog implements Animal {
constructor(public name: string) {}

speak(): void {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Max');
dog.speak(); // Max barks.
Live Playground, Try it Yourself

Abstract Classes vs Interfaces​

Abstract classes and interfaces can both be used to define common structures and behaviors for classes, but they have some differences:

  • Abstract classes can have implementation details, while interfaces only define the structure.
  • A class can extend only one abstract class but can implement multiple interfaces.
  • Abstract classes can have constructors, while interfaces cannot.

Using Abstract Classes with Interfaces​

Abstract classes and interfaces can be combined to create more flexible and reusable code. For example, you can use an interface to define a common structure and an abstract class to provide default behavior for the classes that implement the interface.

TypeScript
interface Animal {
name: string;
speak(): void;
}

abstract class Mammal implements Animal {
constructor(public name: string) {}

abstract speak(): void;

sleep(): void {
console.log(`${this.name} is sleeping.`);
}
}

class Dog extends Mammal {
speak(): void {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Max');
dog.speak(); // Max barks.
dog.sleep(); // Max is sleeping.
Live Playground, Try it Yourself

Conclusion​

In this tutorial, we have explored abstract classes and interfaces in TypeScript, which are essential components of advanced object-oriented programming (OOP). As you continue learning TypeScript, make sure to practice using abstract classes and interfaces to create more flexible, reusable, and maintainable code in your applications.