An abstract class in TypeScript is defined by the abstract
keyword. It’s meant to be derived by other classes and not to be instantiated directly.
The example below has the BaseLogger, which is an abstract class that enforces derived classes to implement its abstract
methods.
abstract class BaseLogger {
abstract log(msg: string): void
}
// Error! Non-abstract class 'DebugLogger' does not implement inherited abstract member 'log' from class 'BaseLogger'.
class DebugLogger extends BaseLogger {
// log method must be implemented
}
Abstract classes are similar to interfaces with methods, but one difference is that it can also contain shared implementations. Note that these do not have the abstract
keyword in front of the method names.
abstract class BaseLogger {
abstract log(msg: string): void
public formatMessage(msg: string): string {
return msg.toLowerCase();
}
}
class DebugLogger extends BaseLogger {
public log(msg: string): void {
const formattedMessage = this.formatMessage(msg);
console.log(msg);
}
}
#software-architecture #software-engineering #typescript #software-development #javascript #programming