Abstract methods let you define a method without a body in a base class. This means child classes must create their own version of this method. It helps make sure all child classes follow the same rules.
Abstract methods in Typescript
abstract class Animal { abstract makeSound(): void; } class Dog extends Animal { makeSound(): void { console.log('Woof!'); } }
An abstract method has no body and ends with a semicolon.
Classes with abstract methods must be declared abstract too.
Car provides its own startEngine method.abstract class Vehicle { abstract startEngine(): void; } class Car extends Vehicle { startEngine(): void { console.log('Car engine started'); } }
Circle implements area to calculate its area.abstract class Shape { abstract area(): number; } class Circle extends Shape { radius: number; constructor(radius: number) { super(); this.radius = radius; } area(): number { return Math.PI * this.radius * this.radius; } }
abstract class Appliance { abstract turnOn(): void; } // Error: Cannot create instance of abstract class // const appliance = new Appliance();
This program shows an abstract class Employee with an abstract method calculateSalary. Two child classes implement this method differently. We create objects and print their salaries.
abstract class Employee { abstract calculateSalary(): number; } class FullTimeEmployee extends Employee { monthlySalary: number; constructor(monthlySalary: number) { super(); this.monthlySalary = monthlySalary; } calculateSalary(): number { return this.monthlySalary; } } class PartTimeEmployee extends Employee { hourlyRate: number; hoursWorked: number; constructor(hourlyRate: number, hoursWorked: number) { super(); this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked; } calculateSalary(): number { return this.hourlyRate * this.hoursWorked; } } const fullTimeEmployee = new FullTimeEmployee(3000); const partTimeEmployee = new PartTimeEmployee(20, 80); console.log('Full-time employee salary:', fullTimeEmployee.calculateSalary()); console.log('Part-time employee salary:', partTimeEmployee.calculateSalary());
Time complexity of calling an abstract method is the same as calling a normal method (O(1)).
Space complexity depends on the class instance size, not the abstract method itself.
Common mistake: Forgetting to implement the abstract method in child classes causes a compile error.
Use abstract methods when you want to enforce a contract for child classes, instead of optional overrides.
Abstract methods define a method without a body in an abstract class.
Child classes must implement all abstract methods.
Abstract classes cannot be instantiated directly.
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
