You are here: Home / Topics / Abstract Class in Typescript

Abstract Class in Typescript

Filed under: TypeScript on 2024-03-18 11:37:35

Abstraction in TypeScript is a concept that allows you to create classes with abstract methods and properties. Abstract classes cannot be instantiated directly but serve as a blueprint for other classes to inherit from.


Example 1:
index.ts:
abstract class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
abstract makeSound(): void;
move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
class Dog extends Animal {
makeSound(): void {
console.log(`${this.name} barks "Woof!"`);
}
}
const myDog = new Dog("Dog1");
myDog.move(10); // Output: Dog1 moved 10 meters.
myDog.makeSound(); // Output: Dog1 barks "Woof!"

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.