TypeScript expands JavaScript’s capabilities by offering robust support for object-oriented programming (OOP) principles, particularly inheritance and polymorphism. Here’s how TypeScript helps you create scalable and powerful applications using these concepts:
Inheritance in TypeScript
Inheritance enables you to build hierarchies between classes, so that child classes inherit members (fields, methods) from parent classes.
Example:
class Animal {
speak() {
console.log('The animal makes a sound');
}
}
class Dog extends Animal {
speak() {
console.log('The dog barks');
}
}
const dog = new Dog();
dog.speak(); // Output: The dog barks
-
extendskeyword establishes the relationship betweenDogandAnimal. - Method overriding allows specialization in child classes.
Polymorphism in TypeScript
Polymorphism allows objects of different classes to be treated as objects of a common parent class, enabling flexibility and reuse.
Example:
class Cat extends Animal {
speak() {
console.log('The cat meows');
}
}
function makeAnimalSpeak(animal: Animal) {
animal.speak();
}
const animals: Animal[] = [new Dog(), new Cat()];
animals.forEach(makeAnimalSpeak);
// Output:
// The dog barks
// The cat meows
- Polymorphic behavior is achieved since
makeAnimalSpeakaccepts anyAnimaltype, lettingDogandCatspecialize behavior.
Key Takeaways
- TypeScript enforces OOP principles at compile time, reducing runtime errors.
- Classes and interfaces further enhance OOP design, allowing solid code architectures.
- TypeScript provides clear syntax for inheritance, overrides, and polymorphic method calls.
By leveraging TypeScript’s OOP features, you can write clearer, reusable, and scalable code for complex applications.
Top comments (0)