What if you could make sure every part of your program follows the rules without writing the same code again and again?
Why Abstract methods in Typescript? - Purpose & Use Cases
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.
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.
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.
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'); } }
abstract class Animal { abstract makeSound(): void; } class Dog extends Animal { makeSound() { console.log('Bark'); } } class Cat extends Animal { makeSound() { console.log('Meow'); } }
Abstract methods make sure every subclass follows the same rules, helping you build clear and reliable programs.
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.
Abstract methods define required methods without implementation.
They enforce consistent behavior across subclasses.
They keep code organized and easier to maintain.
Practice
abstract methods in TypeScript?Solution
Step 1: Understand abstract method definition
Abstract methods declare a method signature without a body inside an abstract class.Step 2: Check subclass requirements
Child classes must provide an implementation for all abstract methods.Final Answer:
They have no body and must be implemented by subclasses. -> Option AQuick Check:
Abstract methods require implementation [OK]
- Thinking abstract methods can be called directly
- Confusing abstract methods with interface methods
- Assuming abstract methods are optional to implement
Solution
Step 1: Recall abstract method syntax
Abstract methods are declared with theabstractkeyword and no body, ending with a semicolon.Step 2: Analyze options
abstract myMethod(): void;matches the correct syntax. Syntaxes that incorrectly include a body are invalid.myMethod(): void;lacks theabstractkeyword.Final Answer:
abstract myMethod(): void; -> Option BQuick Check:
Abstract method syntax = abstract myMethod(): void; [OK]
- Adding method body to abstract methods
- Omitting the abstract keyword
- Using function keyword inside class
abstract class Animal {
abstract makeSound(): string;
}
class Dog extends Animal {
makeSound(): string {
return "Woof!";
}
}
const dog = new Dog();
console.log(dog.makeSound());Solution
Step 1: Understand class hierarchy
Animal is abstract with an abstract methodmakeSound. Dog extends Animal and implementsmakeSoundreturning "Woof!".Step 2: Check instantiation and method call
Dog is instantiated (allowed), and callingmakeSound()returns "Woof!".Final Answer:
"Woof!" -> Option AQuick Check:
Implemented abstract method returns "Woof!" [OK]
- Trying to instantiate abstract class directly
- Forgetting to implement abstract method
- Expecting undefined instead of returned string
abstract class Vehicle {
abstract startEngine(): void;
}
class Car extends Vehicle {
startEngine() {
console.log("Engine started");
}
}
const myCar = new Vehicle();Solution
Step 1: Check instantiation of abstract class
The code tries to create an instance ofVehicle, which is abstract and cannot be instantiated.Step 2: Verify method implementation and class declarations
TheCarclass correctly implementsstartEngine. The method return type is optional in implementation. No need for static method or abstract Car class.Final Answer:
Cannot instantiate abstract class Vehicle. -> Option CQuick Check:
Abstract classes cannot be instantiated [OK]
- Trying to create instance of abstract class
- Thinking method must be static
- Confusing missing return type as error
abstract class Shape {
abstract area(): number;
}
// Choose the correct subclass implementation:Solution
Step 1: Check constructor and super call
class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } correctly callssuper()in constructor, required for subclass of abstract class.Step 2: Verify method signature and implementation
class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } implementsarea()returning a number, matching abstract method signature. Other implementations have errors: one missessuper()and uses an undefined variable, one returns 0 ignoring side, one returns string instead of number.Final Answer:
class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } -> Option DQuick Check:
Correct subclass calls super and matches method signature [OK]
- Omitting super() call in constructor
- Mismatching return types in method
- Using undefined variables inside method
Ready to prove it?
Pass the test and this pattern moves unknown
