Categories
TypeScript Answers

How to declare abstract method in TypeScript?

Spread the love

To declare abstract method in TypeScript, we can use the abstract keyword.

For instance, we write

abstract class Animal {
  constructor(protected name: string) {}
  abstract makeSound(input: string): string;

  move(meters) {
    console.log(this.name, " moved");
  }
}

class Snake extends Animal {
  constructor(name: string) {
    super(name);
  }

  makeSound(input: string): string {
    return input;
  }

  move() {
    console.log("Slithering...");
    super.move(5);
  }
}

to create the Animal abstract class which have some methods that should be implemented when we create a class from it.

Then we create the Snake class that extends the Animal abstract class.

We implement all the methods in the abstract class in the class.

And we use super to reference the abstract class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.