Objects and Classes

TS Abstract Classes

Using Abstract Classes

TypeScript abstract classes define blueprints requiring implementation.

Introduction to Abstract Classes

Abstract classes in TypeScript serve as blueprints for creating specific classes. They allow you to define methods that must be implemented by any derived class, ensuring a consistent API. Unlike interfaces, abstract classes can include implementation code, allowing for shared functionality among derived classes.

Defining an Abstract Class

To define an abstract class in TypeScript, use the abstract keyword. You can define methods within the abstract class that must be implemented by any subclass.

Here's a basic example:

Implementing Abstract Classes

Once an abstract class is defined, it can be extended by other classes. These subclasses must provide concrete implementations for any abstract methods defined in the abstract class. If they fail to do so, TypeScript will raise an error.

Consider the following example:

Abstract Classes vs Interfaces

While both abstract classes and interfaces are used to define contracts in TypeScript, they differ in functionality:

  • Abstract Classes: Can have implementation, constructors, and fields. Use them when you need a base class with some shared code.
  • Interfaces: Only declare methods and properties but do not provide implementation. Use them for defining a contract that can be implemented by any class.

Use Cases for Abstract Classes

Abstract classes are especially useful when you have a group of closely related entities. They help encapsulate common functionality and enforce a specific method structure in subclasses.

For example, in a graphical application dealing with shapes, you could define an abstract class Shape where each subclass must implement a draw() method, yet share logic for calculating area or perimeter.

Previous
Inheritance
Next
Enums