Introduction
Programs often have several kinds of a thing: shapes, employees, payment methods, notifications. They share some behaviour and differ in the rest. Inheritance lets the shared part live in one parent class, and interfaces describe what all kinds can do, so that code can work with any of them through one type. This lesson shows how TypeScript checks both.
How it works
A class that extends another inherits all its members. Its constructor must call super(...), the parent's constructor, before using this:
class Circle extends Shape {
constructor(private r: number) {
super("circle");
}
}
A subclass can override a method by writing its own version. Marking it override makes TypeScript check that the parent really has that method, which catches typos and methods renamed in the parent. Inside an override, super.describe() calls the parent's version. A protected member can be used in the class and its subclasses, but not from outside.
An abstract class is an outline. It cannot be created with new, and it may declare abstract methods that have a signature but no body. Every concrete subclass must write them, or TypeScript reports an error. The abstract class can still have ordinary methods that call the abstract ones: describe() calls this.area(), and each subclass decides what area means.
implements makes a class promise an interface. TypeScript checks that the class has every member, with the right types. Because typing is structural, implementing is a check, not a requirement: any object with a describe() method fits the Describable interface, whether it comes from a class or is a plain object literal.
Polymorphism is the payoff. A Shape[] can hold circles and squares, and s.describe() runs the right code for each object. Code that uses shapes never needs to know which kinds exist.
Example
// An interface, an abstract class and two subclasses: one list, many kinds.
interface Describable {
describe(): string;
}
abstract class Shape implements Describable {
constructor(protected readonly name: string) {}
abstract area(): number; // every subclass must write this
describe(): string {
return this.name + " with area " + this.area().toFixed(1);
}
}
class Circle extends Shape {
constructor(private r: number) {
super("circle");
}
area(): number {
return Math.PI * this.r ** 2;
}
}
class Square extends Shape {
constructor(private side: number) {
super("square");
}
area(): number {
return this.side ** 2;
}
override describe(): string {
return "a " + super.describe();
}
}
const shapes: Shape[] = [new Circle(1), new Square(3)];
for (const s of shapes) console.log(s.describe());
const things: Describable[] = [...shapes, { describe: () => "a plain object" }];
console.log(things.length, things[2].describe());Line by line
Describablesays what any describable thing has: adescribe()method returning a string.Shapeis abstract: it stores a protectedname, leavesarea()to subclasses and writesdescribe()itself.CircleandSquarecallsuperwith their name and write their ownarea().Squareoverridesdescribe()and calls the parent's version withsuper.describe().- A plain object with a
describemethod fitsDescribabletoo.
Expected result
circle with area 3.1
a square with area 9.0
3 a plain object
In the real world
Frameworks give you abstract classes or interfaces to fill in: a test runner's reporter, a game engine's component, a web server's middleware. Codebases often prefer interfaces and small classes to deep inheritance trees, because a change high in a tree affects everything below it. TypeScript's structural typing makes this easy, since anything with the right shape fits an interface.
Common mistakes
- Using this before super(...) in a subclass constructor, which is an error.
- Forgetting to write an abstract method in a subclass; TypeScript reports TS2515.
- Deep inheritance chains that make it hard to know where a method comes from.
- Thinking implements adds code; it only checks, and the class must still write every member.
Best practices
- Write
overrideon every overriding method. - Prefer an interface for "can do" relationships, and inheritance only for real "is a" relationships with shared code.
- Keep fields private or protected, and let subclasses use methods rather than reaching into the parent's data.
Summary
extends makes a subclass that inherits the parent's members; super calls the parent's constructor and methods, and override replaces a method under the compiler's check. Abstract classes give a shared outline whose abstract methods each subclass must write, and implements checks that a class fits an interface. Polymorphism then lets one piece of code work with every kind.
Quick check
Key takeaways
- extends shares code; super reaches the parent's constructor and methods.
- abstract classes define a shared outline and leave some methods to each subclass.
- implements checks that a class fits an interface; any value of that shape fits too.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.