Interfaces are a fundamental tool in object-oriented programming, as they allow us to define the structure and behavior of an object.
An interface in TypeScript allows us to define the structure of an object, specifying the names and types of its properties and methods.
Subsequently, classes can implement this interface (in this case, they must define all the variables and methods included in the interface).
If you want to learn more, check out the Object-Oriented Programming Course
Declaring an interface
To declare an interface in TypeScript, we use the keyword interface followed by the interface name and the properties and methods we want to define. Let’s see an example:
interface Person {
name: string;
age: number;
greet(): void;
}
In this example, we have declared an interface called Persona that defines three properties:
nombreof typestringedadof typenumbersaludarwhich is a method with no return (void).
Implementing an interface in a class
Once we have declared an interface, we can implement it in a class using the keyword implements. This establishes that the class must implement the variables and methods declared by the interface.
Let’s see an example:
class Student implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
In this example, we have declared a class called Estudiante that implements the Persona interface.
Therefore, the Estudiante class must define the properties nombre and edad, as well as the method saludar, as defined in the Persona interface.
Extending interfaces
TypeScript allows the extension of interfaces, enabling the creation of more specific interfaces based on other interfaces.
interface Animal {
name: string;
}
interface Pet extends Animal {
vaccinations: boolean;
}
const pet: Pet = { name: "Firulais", vaccinations: true };
console.log(pet); // { name: "Firulais", vaccinations: true }
Here, Mascota extends Animal, adding the vacunas property. Any object that implements Mascota must also comply with the properties of Animal.
Optional properties
Optional properties are defined by adding a question mark (?) after the property name. This indicates that the property may not be present in the object.
interface Book {
title: string;
author?: string;
}
const book1: Book = { title: "Basic TypeScript" };
const book2: Book = { title: "Advanced TypeScript", author: "Luis Pérez" };
Readonly properties
Readonly properties are defined using the readonly keyword. This ensures the property cannot be modified after its initialization.
interface Point {
readonly x: number;
readonly y: number;
}
const point: Point = { x: 10, y: 20 };
// point.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.
In this example, the properties x and y are readonly and cannot be modified once assigned.
