Language: EN

interfaces-en-typescript

What are Interfaces and how to use them in TypeScript

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 by 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).

Declaring an interface

To declare an interface in TypeScript, we use the interface keyword followed by the name of the interface 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 Person that defines three properties:

  • name of type string
  • age of type number
  • greet which 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 implements keyword. 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 Student that implements the Person interface.

Therefore, the Student class must define the properties name and age, as well as the method greet, just as defined in the Person interface.

Implementation of multiple interfaces

A class can implement multiple interfaces, ensuring that it complies with several contracts.

interface Flyer {
    fly(): void;
}

interface Swimmer {
    swim(): void;
}

class Duck implements Flyer, Swimmer {
    fly(): void {
        console.log("The duck is flying.");
    }

    swim(): void {
        console.log("The duck is swimming.");
    }
}

const duck = new Duck();
duck.fly(); // The duck is flying.
duck.swim(); // The duck is swimming.

In this example, the Duck class implements both Flyer and Swimmer, ensuring that it has the fly and swim methods.

Extending Interfaces

TypeScript allows for 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, Pet extends Animal, adding the vaccinations property. Any object implementing Pet must also fulfill 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: "Juan Pérez" };

Read-only properties

Read-only properties are defined using the readonly keyword. This ensures that 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 read-only and cannot be modified once assigned.