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!"