0
0
Typescriptprogramming~3 mins

Why Abstract methods in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make sure every part of your program follows the rules without writing the same code again and again?

The Scenario

Imagine you are building a program with different types of animals. You want each animal to make a sound, but you have to write the sound code for every animal separately, even if some animals share similar behavior.

The Problem

Writing the same method over and over for each animal is slow and easy to forget or make mistakes. It also makes your code messy and hard to change later.

The Solution

Abstract methods let you define a method that must be created by every animal type, without writing the details upfront. This keeps your code clean and ensures every animal has its own sound method.

Before vs After
Before
class Animal {
  makeSound() {
    // no default, must write in each subclass
  }
}
class Dog extends Animal {
  makeSound() {
    console.log('Bark');
  }
}
class Cat extends Animal {
  makeSound() {
    console.log('Meow');
  }
}
After
abstract class Animal {
  abstract makeSound(): void;
}
class Dog extends Animal {
  makeSound() {
    console.log('Bark');
  }
}
class Cat extends Animal {
  makeSound() {
    console.log('Meow');
  }
}
What It Enables

Abstract methods make sure every subclass follows the same rules, helping you build clear and reliable programs.

Real Life Example

Think of a game where different characters must perform actions like jump or attack. Abstract methods force each character to have these actions, but let them do it their own way.

Key Takeaways

Abstract methods define required methods without implementation.

They enforce consistent behavior across subclasses.

They keep code organized and easier to maintain.