Abstract Classes In TypeScript
Topic | Source |
---|---|
๐ฆ TypeScript | TypeScript course by the native web |
Abstract classes are like interfaces with superpowers. The keyword abstract
makes sure, that you can not instantiate this class. But you can give some default implementations.
abstract class Animal {
breathe (): void { //default implementation
console.log('In and out, and in and out, ...');
}
abstract hunt (): void; // no specific implementation
}
class Dog extends Animal {
hunt (): void {
console.log('Woof, grrr, woof!');
}
}
class Cat extends Animal {
hunt (): void {
console.log('...');
}
}
class Horse extends Animal {
hunt (): void {
throw new Error('Where is my grass?');
}
}
// Compiler error, because Animal is an abstract class
// const anonymous = new Animal();
const dark = new Horse();
dark.breathe();
dark.hunt();
export {}