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.
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 parametername
typed asstring
and a methoddescribe()
that returns a string. This sets up a reusable structure with both data and behavior.Line 2: The
name
property is markedprotected
, which means it's accessible inEmployee
and any subclass likeManager
, but not from outside the class hierarchy. This helps maintain encapsulation, while still allowing subclass customization.Line 9: The
Manager
class extendsEmployee
using theextends
keyword. This gives it access to all the public and protected members of ...