0
0
Typescriptprogramming~3 mins

Why Abstract classes in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could create a perfect plan that every part of your program must follow, saving you from messy, repeated code?

The Scenario

Imagine you are building a game with different types of characters like warriors and mages. You want each character to have some common actions like moving and attacking, but each type does these actions differently. Without a clear plan, you might write the same code again and again for each character, or forget to add important actions.

The Problem

Writing repeated code for each character wastes time and causes mistakes. If you forget to add an action to one character, the game breaks. It's hard to keep track of what every character should do, and changing common behavior means updating many places manually.

The Solution

Abstract classes let you create a blueprint for characters with common actions defined but not fully implemented. Each character class then fills in the details. This way, you write shared code once and ensure every character follows the same rules, reducing errors and saving time.

Before vs After
Before
class Warrior {
  move() { /* code */ }
  attack() { /* code */ }
}
class Mage {
  move() { /* code */ }
  attack() { /* code */ }
}
After
abstract class Character {
  abstract move(): void;
  abstract attack(): void;
}
class Warrior extends Character {
  move() { /* code */ }
  attack() { /* code */ }
}
class Mage extends Character {
  move() { /* code */ }
  attack() { /* code */ }
}
What It Enables

Abstract classes make your code organized and safe by forcing all related classes to share the same structure while allowing their own unique behavior.

Real Life Example

Think of a car factory where every car must have an engine and wheels, but each model has different designs. An abstract class is like the factory blueprint ensuring every car has these parts, while letting each model customize how they work.

Key Takeaways

Abstract classes provide a shared blueprint for related classes.

They prevent code duplication and enforce consistent structure.

They allow different classes to implement their own specific behavior.