In this tutorial, we will cover the concept of abstract classes and interfaces in TypeScript. Understanding these concepts will help you create more structured and uniform code in TypeScript. By the end of this tutorial, you will have a solid understanding of how to define and work with abstract classes and interfaces.
What you will learn:
Prerequisites:
Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members.
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('Moving...');
}
}
In the above example, Animal is an abstract class that has an abstract method makeSound. It also has a normal method move.
Remember:
An interface is a syntactical contract that an entity should conform to. They are used to define the structure of variables, functions, classes or objects.
interface Animal {
name: string;
age: number;
makeSound(): void;
}
In the above example, Animal is an interface that expects any object implementing it to have a name, age, and a function makeSound.
Remember:
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('Moving...');
}
}
class Dog extends Animal {
makeSound() {
console.log('Barking...');
}
}
const myDog = new Dog();
myDog.makeSound(); // Barking...
myDog.move(); // Moving...
In the above example, Dog is a class that extends the abstract class Animal. It provides the implementation for the makeSound method. We can create an instance of Dog and call the makeSound and move methods.
interface Animal {
name: string;
age: number;
makeSound(): void;
}
class Dog implements Animal {
name = 'Tommy';
age = 5;
makeSound() {
console.log('Barking...');
}
}
const myDog = new Dog();
console.log(myDog.name); // Tommy
myDog.makeSound(); // Barking...
Here, Dog is a class that implements the Animal interface. It provides values for name, age and a method makeSound.
In this tutorial, we explored abstract classes and interfaces in TypeScript. We learned how to define and use them, and looked at some practical examples.
Key Points:
For further learning, you can explore:
Exercise 1: Create an abstract class Shape with methods calculateArea and calculatePerimeter. Then, implement this abstract class in a Circle class.
Exercise 2: Create an interface Vehicle with properties speed and model, and a method getDetails(). Then, create a Car class that implements this interface.
Remember, practice is the key to mastering any concept. Happy coding!