How to declare abstract method in TypeScript?

Sometimes, we want to declare abstract method in TypeScript.

In this article, we’ll look at how to declare abstract method in TypeScript.

How to declare abstract method in TypeScript?

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.

Conclusion

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