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 is 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 block of code that contains its members.

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

class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

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

In this example,

  • class Person: Defines a new class called Person.
  • name: string and age: number: Are properties of the class. They are defined with a data type that specifies what kind of values they can store.
  • constructor(name: string, age: number): Is a special method called a constructor that is invoked when creating a new instance of the class. It initializes the properties name and age.
  • greet(): 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 Person class to define two instances,

const person1 = new Person("Luis", 30);
person1.greet();  // Output: Hello, my name is Luis and I am 30 years old.

const person2 = new Person("Ana", 25);
person2.greet();  // Output: Hello, my name is Ana and I am 25 years old.

In this example,

  • new Person("Luis", 30): Creates a new instance of the Person class, calling the constructor with the arguments "Luis" and 30.
  • person1.greet(): Calls the greet method of the person1 object, which prints a greeting message using the values of its properties.

And the same would occur for the case of 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 Car {
    brand: string;
    model: string;
    year: number;

    constructor(brand: string, model: string, year: number) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    describe(): void {
        console.log(`The car is a ${this.brand} ${this.model} from the year ${this.year}.`);
    }
}

const myCar = new Car("Toyota", "Corolla", 2021);
myCar.describe();  // 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 Book {
    title: string;
    author: string;

    constructor(title: string, author: string) {
        this.title = title;
        this.author = author;
    }
}

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

In this example, the Book class defines a constructor that receives two parameters: title, author. 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 in the constructor parameters.

Here is the same example using this simplified form:

class Book {
    constructor(public title: string, public author: string) {
        }
}

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

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