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.
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
Tablethat extends theProductclass. Don't add any additional implementation forTableat 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
Tableclass and invoke thelogmethod as follows:
const table = new Table("Table", 400, 4);table.log();- Override the
logmethod in theTableclass so that it logs out the number of legs as well as thenameandprice.
- Open the console and check the
logmethod in thetablevariable now logslegsas well asnameandprice.
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
Productclass from being instantiated by consumers.
- Verify that the
Productclass can't be instantiated by adding the following:
const product = new Product("Chair", 100);A type error occurs as we expect:
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.
