Learn TypeScript

Extending classes

Extending classes

In this lesson, we will learn how a class can extend another class and add additional functionality.

Syntax for extending classes

The syntax for extending a class is as follows:

class ClassName extends AnotherClassName {
...
}

In the above example, ClassName is extending AnotherClassName.

An example of extending a class

We are going to explore extending a class in an exercise.

TypeScriptOpen exercise in CodeSandbox

The code contains a Product class that is familiar from previous lessons. We are going to create a new class by extending the Product class.

  • Create a class called Table that extends the Product class. Don't add any additional implementation for Table at the moment.
  • Add the following constructor to Table:
class Table extends Product {
constructor(public name: string, public price: number, public legs: number) {}
}
🤔

Notice that a type error is raised. What is the problem?

  • Resolve the problem.
  • Consume the Table class and invoke the log method as follows:
const table = new Table("Table", 400, 4);
table.log();
  • Override the log method in the Table class so that it logs out the number of legs as well as the name and price.
  • Open the console and check the log method in the table variable now logs legs as well as name and price.

Class extend

Nice!

Using abstract classes

There are times when we don't want consumers to create instances of a class. We can do this in TypeScript by using the abstract keyword.

abstract class ClassName {
...
}
  • Stop the Product class from being instantiated by consumers.
  • Verify that the Product class can't be instantiated by adding the following:
const product = new Product("Chair", 100);

A type error occurs as we expect:

Abstract class error

Good stuff!

Summary

Extending a class is a way of creating a class similar to another class but with additional functionality. Abstract classes are useful for low-level classes when we don't want consumers to interact with them directly.

© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more