Abstract Methods in TypeScript
What you'll learn: How to declare methods in abstract classes that subclasses must implement, creating enforceable contracts across your inheritance hierarchy.
The Core Concept
Abstract methods are method declarations without implementations. When you mark a method as abstract, you're saying: "Every concrete class that extends this base class must provide its own implementation of this method."
Think of abstract methods like blank spots on a form that must be filled in. The base class defines what needs to exist, but not how it should work—that's the responsibility of each subclass.
How Abstract Methods Work
Since you've already learned about abstract classes, you know they can't be instantiated directly. Abstract methods fit perfectly into this picture: they're method signatures that exist only at compile time to enforce structure.
abstract class PaymentProcessor {
// Abstract method - no implementation
abstract processPayment(amount: number): void;
// Regular method - has implementation
logTransaction(amount: number): void {
console.log(`Processing ${amount}`);
}
}
Now any class extending PaymentProcessor must provide a processPayment implementation:
class CreditCardProcessor extends PaymentProcessor {
processPayment(amount: number): void {
console.log(`Charging card: $${amount}`);
}
}
class PayPalProcessor extends PaymentProcessor {
processPayment(amount: number): void {
console.log(`PayPal transaction: $${amount}`);
}
}
If you forget to implement the abstract method, TypeScript immediately catches it at compile time—you can't create an incomplete subclass.
Why Abstract Methods Matter
Abstract methods let you design polymorphic systems where different implementations share a common interface. You define the "shape" of behavior in the base class, then each subclass fills in the specific details. This creates type-safe contracts without restricting how each subclass accomplishes its task.
Key Takeaway: Abstract methods are unimplemented method declarations in abstract classes that force all concrete subclasses to provide their own implementations, ensuring consistent APIs across an inheritance hierarchy.