TypeScript, a superset of JavaScript, introduces strong typing and object-oriented programming features, including classes and inheritance. By mastering these concepts, you can create scalable and maintainable code. Let’s dive into some practical examples.
First, let’s create a simple class called Animal:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): string {
return `${this.name} makes a sound.`;
}
}
Animal.name.name property.makeSound method returns a string indicating the animal’s sound.Now, let’s create a subclass Dog that extends the Animal class:
class Dog extends Animal {
makeSound(): string {
return `${this.name} barks.`;
}
}
Dog class extends the Animal class, inheriting its properties and methods.makeSound method is overridden to provide a specific implementation for dogs.Let’s see how we can use these classes:
const myDog = new Dog('Buddy');
console.log(myDog.makeSound()); // Output: Buddy barks.
Dog class with the name Buddy.makeSound method, which outputs the specific sound for the dog.We can expand on our Dog class by adding more properties and methods:
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name); // Call the parent class constructor
this.breed = breed;
}
fetch(): string {
return `${this.name} is fetching the ball.`;
}
}
breed property is added to the Dog class.super(name) to invoke the constructor of the Animal class.fetch method provides functionality specific to dogs.In this article, we explored the basics of classes and inheritance in TypeScript. We created a simple Animal class, extended it with a Dog class, and demonstrated how to add additional properties and methods. Understanding these concepts will greatly enhance your ability to write organized and reusable TypeScript code.