Bird
Raised Fist0
Typescriptprogramming~5 mins

Abstract methods in Typescript

Choose your learning style10 modes available
Introduction

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.

When you want to create a base class that sets a rule for child classes to follow.
When you want to force child classes to provide their own specific behavior for a method.
When you design a system where different objects share a common method name but have different actions.
When you want to prevent creating instances of a base class that is incomplete by itself.
Syntax
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.

Examples
Child class Car provides its own startEngine method.
Typescript
abstract class Vehicle {
  abstract startEngine(): void;
}

class Car extends Vehicle {
  startEngine(): void {
    console.log('Car engine started');
  }
}
Child class Circle implements area to calculate its area.
Typescript
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;
  }
}
You cannot create an instance of an abstract class directly.
Typescript
abstract class Appliance {
  abstract turnOn(): void;
}

// Error: Cannot create instance of abstract class
// const appliance = new Appliance();
Sample Program

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.

Typescript
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());
OutputSuccess
Important Notes

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.

Summary

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

(1/5)
1. What is true about abstract methods in TypeScript?
easy
A. They have no body and must be implemented by subclasses.
B. They can be called directly without implementation.
C. They can only be used in interfaces, not classes.
D. They are optional to implement in child classes.

Solution

  1. Step 1: Understand abstract method definition

    Abstract methods declare a method signature without a body inside an abstract class.
  2. Step 2: Check subclass requirements

    Child classes must provide an implementation for all abstract methods.
  3. Final Answer:

    They have no body and must be implemented by subclasses. -> Option A
  4. Quick Check:

    Abstract methods require implementation [OK]
Hint: Abstract methods have no body and force subclass implementation [OK]
Common Mistakes:
  • Thinking abstract methods can be called directly
  • Confusing abstract methods with interface methods
  • Assuming abstract methods are optional to implement
2. Which of the following is the correct syntax to declare an abstract method in a TypeScript abstract class?
easy
A. abstract myMethod() { }
B. abstract myMethod(): void;
C. myMethod(): void;
D. abstract function myMethod() {}

Solution

  1. Step 1: Recall abstract method syntax

    Abstract methods are declared with the abstract keyword and no body, ending with a semicolon.
  2. Step 2: Analyze options

    abstract myMethod(): void; matches the correct syntax. Syntaxes that incorrectly include a body are invalid. myMethod(): void; lacks the abstract keyword.
  3. Final Answer:

    abstract myMethod(): void; -> Option B
  4. Quick Check:

    Abstract method syntax = abstract myMethod(): void; [OK]
Hint: Abstract methods have no body and end with a semicolon [OK]
Common Mistakes:
  • Adding method body to abstract methods
  • Omitting the abstract keyword
  • Using function keyword inside class
3. What will be the output of the following TypeScript code?
abstract class Animal {
  abstract makeSound(): string;
}

class Dog extends Animal {
  makeSound(): string {
    return "Woof!";
  }
}

const dog = new Dog();
console.log(dog.makeSound());
medium
A. "Woof!"
B. Error: Cannot instantiate abstract class
C. undefined
D. Error: makeSound method not implemented

Solution

  1. Step 1: Understand class hierarchy

    Animal is abstract with an abstract method makeSound. Dog extends Animal and implements makeSound returning "Woof!".
  2. Step 2: Check instantiation and method call

    Dog is instantiated (allowed), and calling makeSound() returns "Woof!".
  3. Final Answer:

    "Woof!" -> Option A
  4. Quick Check:

    Implemented abstract method returns "Woof!" [OK]
Hint: Abstract class can't instantiate, but subclass can [OK]
Common Mistakes:
  • Trying to instantiate abstract class directly
  • Forgetting to implement abstract method
  • Expecting undefined instead of returned string
4. Identify the error in the following TypeScript code:
abstract class Vehicle {
  abstract startEngine(): void;
}

class Car extends Vehicle {
  startEngine() {
    console.log("Engine started");
  }
}

const myCar = new Vehicle();
medium
A. startEngine method must be static.
B. Missing return type in startEngine method.
C. Cannot instantiate abstract class Vehicle.
D. Car class must be abstract.

Solution

  1. Step 1: Check instantiation of abstract class

    The code tries to create an instance of Vehicle, which is abstract and cannot be instantiated.
  2. Step 2: Verify method implementation and class declarations

    The Car class correctly implements startEngine. The method return type is optional in implementation. No need for static method or abstract Car class.
  3. Final Answer:

    Cannot instantiate abstract class Vehicle. -> Option C
  4. Quick Check:

    Abstract classes cannot be instantiated [OK]
Hint: Abstract classes cannot be instantiated directly [OK]
Common Mistakes:
  • Trying to create instance of abstract class
  • Thinking method must be static
  • Confusing missing return type as error
5. Given the abstract class below, which implementation correctly uses abstract methods to calculate area?
abstract class Shape {
  abstract area(): number;
}

// Choose the correct subclass implementation:
hard
A. class Square extends Shape { constructor(private side: number) { super(); } area(): string { return `${this.side}`; } }
B. class Square extends Shape { constructor(private side: number) {} area() { return side * side; } }
C. class Square extends Shape { area(): number { return 0; } }
D. class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } }

Solution

  1. Step 1: Check constructor and super call

    class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } correctly calls super() in constructor, required for subclass of abstract class.
  2. Step 2: Verify method signature and implementation

    class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } implements area() returning a number, matching abstract method signature. Other implementations have errors: one misses super() and uses an undefined variable, one returns 0 ignoring side, one returns string instead of number.
  3. Final Answer:

    class Square extends Shape { constructor(private side: number) { super(); } area(): number { return this.side * this.side; } } -> Option D
  4. Quick Check:

    Correct subclass calls super and matches method signature [OK]
Hint: Subclass must call super() and match abstract method signature [OK]
Common Mistakes:
  • Omitting super() call in constructor
  • Mismatching return types in method
  • Using undefined variables inside method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard