...

/

Inheritance and Abstract Classes

Inheritance and Abstract Classes

Use inheritance and abstract classes to write scalable, contract-driven TypeScript code that enforces structure without sacrificing flexibility.

Class hierarchies let us model shared structure across types. But in JavaScript, inheritance is loose: we can override anything, miss fields, and instantiate things we shouldn’t. TypeScript brings discipline to this model. It tightens the rules and clarifies the design without slowing us down.

In this lesson, we’ll unlock TypeScript’s inheritance tools: extending classes, enforcing method signatures, and defining abstract contracts that subclasses are required to complete.

Let’s make our classes do more.

Extending classes with extends

When we extend a class, we reuse its fields and methods and specialize them when needed. TypeScript guarantees that subclassing aligns with the base class structure.

In the following example, we’ll define a base class Employee with a field and method, then extend it with a subclass Manager that:

  • Adds a new field, department.

  • Calls the base constructor using super().

  • Overrides the describe() method with more specific behavior.

This example shows how TypeScript lets us extend structure while keeping type safety fully intact. Let’s look at the code.

Press + to interact
TypeScript 5.8.3
Files
class Employee {
constructor(protected name: string) {}
describe(): string {
return `${this.name} works here.`;
}
}
class Manager extends Employee {
constructor(name: string, public department: string) {
super(name);
}
describe(): string {
return `${this.name} manages the ${this.department} department.`;
}
}
const m = new Manager("Alana", "Engineering");
console.log(m.describe()); // Alana manages the Engineering department.

Explanation:

  • Lines 1–7: We define a class Employee that includes a constructor parameter name typed as string and a method describe() that returns a string. This sets up a reusable structure with both data and behavior.

  • Line 2: The name property is marked protected, which means it's accessible in Employee and any subclass like Manager, but not from outside the class hierarchy. This helps maintain encapsulation, while still allowing subclass customization.

  • Line 9: The Manager class extends Employee using the extends keyword. This gives it access to all the public and protected members of ...

Access this course and 1400+ top-rated courses and projects.