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
Table
that extends theProduct
class. Don't add any additional implementation forTable
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 thelog
method as follows:
const table = new Table("Table", 400, 4);table.log();
- Override the
log
method in theTable
class so that it logs out the number of legs as well as thename
andprice
.
- Open the console and check the
log
method in thetable
variable now logslegs
as well asname
andprice
.
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:
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.