What if you could create a perfect plan that every part of your program must follow, saving you from messy, repeated code?
Why Abstract classes in Typescript? - Purpose & Use Cases
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.
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.
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.
class Warrior { move() { /* code */ } attack() { /* code */ } } class Mage { move() { /* code */ } attack() { /* code */ } }
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 */ } }
Abstract classes make your code organized and safe by forcing all related classes to share the same structure while allowing their own unique behavior.
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.
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.
Practice
abstract class in TypeScript?Solution
Step 1: Understand abstract class instantiation rules
Abstract classes cannot be instantiated directly, so you cannot create objects from them usingnew.Step 2: Compare other options
Abstract classes can have implemented methods, are different from interfaces, and cannot be instantiated withnew.Final Answer:
You cannot create an instance of an abstract class directly. -> Option CQuick Check:
Abstract class instantiation = not allowed [OK]
- Thinking abstract classes are interfaces
- Assuming abstract classes can't have implemented methods
- Trying to instantiate abstract classes directly
Solution
Step 1: Recall TypeScript abstract class syntax
The correct syntax places the keywordabstractbeforeclass, followed by the class name.Step 2: Check each option
Only abstract class Vehicle {} correctly usesabstract class Vehicle {}. Others have incorrect keyword order.Final Answer:
abstract class Vehicle {} -> Option AQuick Check:
Abstract class syntax =abstract class Name {}[OK]
- Placing 'abstract' after 'class'
- Mixing keyword order
- Omitting 'abstract' keyword
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('Moving');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Bark');
}
}
const dog = new Dog();
dog.makeSound();
dog.move();Solution
Step 1: Understand class inheritance and method calls
The classDogextendsAnimaland implementsmakeSound(). Callingdog.makeSound()prints 'Bark'.Step 2: Check the
Themove()method callmove()method is implemented inAnimaland prints 'Moving'. Callingdog.move()prints 'Moving'.Final Answer:
Bark Moving -> Option DQuick Check:
Subclass methods run, abstract class methods inherited [OK]
- Thinking abstract class instance is created
- Confusing method call order
- Expecting errors on calling inherited methods
abstract class Shape {
abstract area(): number;
}
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super();
this.radius = radius;
}
}Solution
Step 1: Check abstract method implementation
The abstract classShapedeclares an abstract methodarea(). Any subclass must implement this method.Step 2: Verify Circle class methods
TheCircleclass does not implementarea(), so this causes a compile-time error.Final Answer:
Circle must implement the abstract method area() -> Option AQuick Check:
Abstract methods require subclass implementation [OK]
- Forgetting to implement abstract methods
- Thinking super() call is not mandatory when base has no constructor
- Confusing abstract methods with optional methods
abstract class Shape {
abstract area(): number;
}
// Choose the correct Rectangle class implementationSolution
Step 1: Check constructor and super() call
SinceShapehas no constructor, callingsuper()is required before usingthisin the subclass constructor.Step 2: Verify area() method correctness
class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } area(): number { return this.width * this.height; } } correctly implementsarea()returning width * height, which is the rectangle's area.Step 3: Check other options for errors
class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { this.width = width; this.height = height; } area(): number { return this.width + this.height; } } return width + height, which is incorrect for area. class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } } lacksarea()implementation, causing error.Final Answer:
class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } area(): number { return this.width * this.height; } } -> Option BQuick Check:
Correct area method and constructor = class Rectangle extends Shape { width: number; height: number; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } area(): number { return this.width * this.height; } } [OK]
- Returning sum instead of product for area
- Omitting abstract method implementation
- Forgetting to assign constructor parameters
Ready to prove it?
Pass the test and this pattern moves unknown
