Language: EN

clases-en-typescript

What are classes and how to use them in TypeScript

Classes in TypeScript provide a structured way to define objects with associated properties and methods.

Classes are fundamental in object-oriented programming, as they allow us to define objects that encapsulate related data and behaviors.

If you want to learn more, here’s the link to the Object-Oriented Programming Course 👇

Definition of a Class

In TypeScript, you can define a class using the class keyword, followed by the class name and a code block that contains its members.

Let’s look at a simple example of a Person class:

class Persona {
    nombre: string;
    edad: number;

    constructor(nombre: string, edad: number) {
        this.nombre = nombre;
        this.edad = edad;
    }

    saludar(): void {
        console.log(`Hello, my name is ${this.nombre} and I am ${this.edad} years old.`);
    }
}

In this example,

  • class Persona: Defines a new class called Persona.
  • nombre: string and edad: number: Are properties of the class. They are defined with a data type that specifies what kind of values they can store.
  • constructor(nombre: string, edad: number): Is a special method called a constructor that is invoked when creating a new instance of the class. It initializes the properties nombre and edad.
  • saludar(): void: Is a method that does not return any value (void) and prints a greeting to the console.

Instantiating a Class

Once we have a class defined, we can create instances of it using the new keyword.

Each instance will be a separate object that has its own properties and methods. For example, let’s use our Persona class to define two instances,

const persona1 = new Persona("Juan", 30);
persona1.saludar();  // Output: Hello, my name is Juan and I am 30 years old.

const persona2 = new Persona("Ana", 25);
persona2.saludar();  // Output: Hello, my name is Ana and I am 25 years old.

In this example,

  1. new Persona("Juan", 30): Creates a new instance of the Persona class, calling the constructor with the arguments "Juan" and 30.
  2. persona1.saludar(): Calls the saludar method of the persona1 object, which prints a greeting message using the values of its properties.

And the same would happen for Ana.

Properties and Methods

The properties and methods of a class can be defined within the class itself by adding them in the body of the class. For example,

class Coche {
    marca: string;
    modelo: string;
    anio: number;

    constructor(marca: string, modelo: string, anio: number) {
        this.marca = marca;
        this.modelo = modelo;
        this.anio = anio;
    }

    describir(): void {
        console.log(`The car is a ${this.marca} ${this.modelo} from the year ${this.anio}.`);
    }
}

const miCoche = new Coche("Toyota", "Corolla", 2021);
miCoche.describir();  // Output: The car is a Toyota Corolla from the year 2021.

Constructor

The constructor is a special method that is automatically invoked when creating a new instance of a class.

Its main purpose is to initialize the properties of the object with the values provided during instantiation.

For example,

class Libro {
    titulo: string;
    autor: string;

    constructor(titulo: string, autor: string) {
        this.titulo = titulo;
        this.autor = autor;
    }
}

const libro1 = new Libro("One Hundred Years of Solitude", "Gabriel García Márquez");

In this example, the Libro class defines a constructor that takes two parameters: titulo, autor. These parameters are used to initialize the corresponding properties of the class.

Simplified Form

TypeScript offers a more concise way to define constructors using access modifiers directly on the constructor parameters.

Here is the same example using this simplified form:

class Libro {
    constructor(public titulo: string, public autor: string) {
        }
}

const libro1 = new Libro("One Hundred Years of Solitude", "Gabriel García Márquez");
console.log(libro1);

This form simplifies the code by combining the declaration and initialization of properties in a single line