Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 96 ยท Objects and Classes

Inheritance and Abstract Classes

Learn class inheritance in TypeScript - extends and super, the override keyword with noImplicitOverride, abstract classes and methods, and implementing interfaces.

Inheritance lets one class build on another. A subclass written with extends gets every field and method of its base class, can add its own, and can override existing methods to change how they behave. JavaScript has supported this since ES2015 (see Inheritance); TypeScript adds checks that make it safer: overrides must stay type-compatible, the override keyword catches renamed methods, and abstract classes let you define a base class that says what subclasses must provide without saying how.

This lesson covers all of that, plus implements, the way a class promises to satisfy an interface. It builds on Classes and Access Modifiers, whose protected members are designed for exactly this situation.

extends and super

A subclass inherits everything from its base class. If it has its own constructor, the constructor must call super(...) with the base constructor's arguments before it touches this:

TypeScript A base class and two subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Several things are happening:

  • Manager passes name and baseSalary up with super(name, baseSalary) and keeps bonusRate for itself (a parameter property).
  • Intern has no constructor at all, so it inherits Employee's constructor and its parameter types.
  • super.monthlyPay() calls the base class version from inside an override.
  • The array has type Employee[], but each call runs the subclass's own version. That's polymorphism: callers work with the base type and get the right behavior for each object. Note how describe(), defined once in Employee, calls the overridden monthlyPay().

Forgetting super() or using this before it is a compile error (and a runtime ReferenceError in plain JavaScript):

TypeScript Using this before super (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(9,5): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. Move the super('square') call to the first line of the constructor.

Overrides must stay compatible

A subclass instance can be used anywhere the base class is expected, so its overrides must accept what the base accepts and return something the base's callers can handle. TypeScript checks this:

TypeScript An incompatible override (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error explains the rule: Property 'format' in type 'BrokenFormatter' is not assignable to the same property in base type 'Formatter'. (TS2416), with the detail that number isn't assignable to string. Code holding a Formatter would call .toUpperCase() on the result and crash. Allowed overrides may return a narrower type (for example a string literal type), accept more optional parameters, or accept a wider parameter type such as number | string.

The override keyword

You may have noticed the override keyword in the first example. It's optional, but it states that a method is meant to replace a base class method, and TypeScript then checks that such a method really exists. That catches a nasty class of bugs: someone renames a base method, and every "override" silently becomes a new, unused method.

TypeScript override catches a renamed base method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

main.ts(8,12): error TS4117: This member cannot have an 'override' modifier because it is not declared in the base class 'Plugin'. Did you mean 'onStart'? (When no similar name exists, the same message comes without the suggestion, as error TS4113.) Without override, this would compile and quietly print default start.

The keyword only helps if people use it. The compiler option noImplicitOverride makes it mandatory: overriding a member without writing override becomes error TS4114 ("This member must have an 'override' modifier because it overrides a member in the base class ..."). It isn't part of strict (and is off in our editor), but it's a cheap, valuable setting for any code base that uses inheritance; see The tsconfig.json File. Like other modifiers, override is erased at compile time.

Abstract classes

Sometimes a base class only makes sense as a starting point. A generic Shape can't compute its area, but every real shape can, and they all share code like describe(). Mark such a class abstract:

  • An abstract class can't be instantiated with new.
  • It can declare abstract methods and properties: signatures with no body, which every concrete subclass must implement.
  • It can also contain normal, fully implemented members that subclasses inherit.
TypeScript An abstract base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

describe() is written once in Shape and works for every subclass because it relies only on the abstract members. This is the template method pattern: the base class defines the algorithm, the subclasses fill in the steps. Implementing an abstract member doesn't need the override keyword (you may still write it, and noImplicitOverride doesn't require it).

The compiler enforces both rules:

TypeScript Abstract class mistakes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You get two errors: main.ts(5,7): error TS2515: Non-abstract class 'Triangle' does not implement inherited abstract member area from class 'Shape'. and main.ts(11,11): error TS2511: Cannot create an instance of an abstract class.

Abstract classes are a TypeScript feature: in the emitted JavaScript, Shape is an ordinary class, and the abstract members simply disappear. Only the compiler stops you from calling new Shape().

An abstract class can have a constructor (subclasses call it with super(...)), fields, protected helpers and static members. That's what separates it from an interface, which can describe a shape but never contains code.

implements: promising an interface

extends inherits code. implements inherits nothing; it's a promise that the class satisfies an interface, checked by the compiler. A class can extend only one class but implement any number of interfaces:

TypeScript Implementing several interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If Version lacked print(), the class declaration itself would report error TS2420 ("Class 'Version' incorrectly implements interface 'Printable'."), right where the mistake is, instead of somewhere far away where a Version is passed as a Printable.

Two common misunderstandings:

  • implements doesn't change the class's type. It only checks it. Method parameters aren't contextually typed from the interface, so you still annotate them in the class.
  • Because typing is structural, a class that has the right members can be used as a Printable even without implements. The keyword is about documentation and early, local error messages. Classes, Interfaces and Structural Typing explores this further.

Extending built-in classes

You can extend built-ins like Error, Map or Array. Custom errors are the most useful case: they let callers recognize a failure with instanceof and carry extra data:

TypeScript A custom Error subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

name is declared with override because Error already has a name property. Notice the explicit : string in HttpError. Without it, a readonly field initialized with 'HttpError' gets the literal type 'HttpError', and then NotFoundError's name = 'NotFoundError' would be an incompatible override (error TS2416: Type '"NotFoundError"' is not assignable to type '"HttpError"'.). Base classes meant to be extended should give such fields the wider type. ErrorOptions is the built-in type for the second Error argument, whose cause property chains errors. Error Handling builds on this.

When to use inheritance

Inheritance is powerful but couples classes tightly: a change in a base class affects every subclass. Some guidelines:

  • Use it for real "is-a" relationships with shared behavior: a Manager is an Employee, a NotFoundError is an HttpError.
  • Keep hierarchies shallow. One or two levels is typical; deep trees are hard to change.
  • Prefer interfaces + composition when classes only share a shape, or when you'd need behavior from two parents. Pass helper objects in rather than inheriting them. (JavaScript's composition lesson shows the pattern.)
  • Make base-class extension points explicit: abstract methods for what subclasses must provide, protected members for what they may use, and override + noImplicitOverride everywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a subclass constructor, what must happen before you use this?

    The base class creates and initializes the object, so super() must run first. Using this earlier is error TS17009.
  2. 2. A subclass declares override save(): void but the base class has no save method. What happens?

    override asks the compiler to verify that a base member exists, which catches renamed or misspelled methods.
  3. 3. abstract class Repo { abstract find(id: number): string; } Which line compiles?

    A concrete subclass must implement find with a compatible type. new Repo() is TS2511, an empty subclass is TS2515, and returning a number breaks the string return type.
  4. 4. What does class A implements I change about the type of A?

    implements is purely a check. Thanks to structural typing, a class with matching members is usable as I even without the clause.
  5. 5. A base method returns string. Which override return type is allowed?

    An override may return a narrower type, because every 'ok' | 'error' is a string. Wider or unrelated types would break callers that expect a string.

Summary

  • class B extends A inherits A's members; a subclass constructor must call super(...) before using this (TS17009). super.method() calls the base version.
  • Overrides must be type-compatible with the base member (TS2416): accept at least as much, return at most as much.
  • The override keyword checks that a base member exists (TS4113/TS4117); noImplicitOverride makes it mandatory (TS4114).
  • Abstract classes can't be instantiated (TS2511) and declare abstract members that concrete subclasses must implement (TS2515); concrete members can build on them (template method pattern).
  • implements checks a class against one or more interfaces without changing its type.
  • Extending Error with extra fields and cause gives callers precise instanceof checks. Keep hierarchies shallow and prefer composition when classes only share a shape.

Next: Classes, Interfaces and Structural Typing