Language: EN

metodos-variables-estaticos-en-typescript

Static Methods and Variables in TypeScript

In TypeScript, static methods and variables are those that belong to the class itself rather than to a specific instance of the class.

They are used to define behaviors that are related to the class as a whole, rather than to individual instances.

Static Methods

A static method is a method that is defined with the static keyword.

class Calculator {
    static add(a: number, b: number): number {
        return a + b;
    }

    static subtract(a: number, b: number): number {
        return a - b;
    }
}

// Using static methods
console.log(Calculator.add(5, 3)); // Output: 8
console.log(Calculator.subtract(5, 3)); // Output: 2

In this example, add and subtract are static methods that perform mathematical operations. They are accessed directly from the Calculator class, without the need to create an instance.

Static methods do not have access to instance properties (this), as they are associated with the class itself

Static Variables

A static variable, like static methods, belongs to the class rather than to individual instances. Static variables can be used to store values that are common to all instances of the class.

class Configuration {
    static readonly API_URL: string = "https://api.example.com";
    static readonly MAX_ATTEMPTS: number = 5;
}

// Using static variables
console.log(Configuration.API_URL);         // Output: https://api.example.com
console.log(Configuration.MAX_ATTEMPTS);    // Output: 5

In this example, API_URL and MAX_ATTEMPTS are static variables defined within the Configuration class. These variables can be accessed directly through the class, without the need to instantiate it.

Inheritance of Static Methods

Static methods can be inherited by derived classes.

class Base {
    static message(): void {
        console.log("Message from the Base class.");
    }
}

class Derived extends Base {
    static message(): void {
        console.log("Message from the Derived class.");
    }
}

Base.message();     // Output: Message from the Base class.
Derived.message(); // Output: Message from the Derived class.

Common Use Cases

Utilities and Helper Functions

Static methods are ideal for defining utilities and helper functions that do not need access to instance properties.

For example, we could define static methods to perform unit conversions, mathematical calculations, or string manipulation.

class Converter {
    static metersToKilometers(meters: number): number {
        return meters / 1000;
    }
}

console.log(Converter.metersToKilometers(5000)); // Output: 5

Factory Methods

In some cases, static methods are used to create instances of the class with certain conditions or configurations.

These methods, sometimes called factory methods, can encapsulate the logic for creating instances.

class User {
    name: string;
    age: number;

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

    static createUser(name: string, age: number): User {
        if (age < 18) {
            throw new Error('The user must be over 18 years old.');
        }
        return new User(name, age);
    }
}

const user1 = User.createUser("Ana", 22); // Correct
console.log(user1);

const user2 = User.createUser("Luis", 16); // Throws an error

Class Constants

Static methods can also be used to access constants or configurations related to the class. Although they are not strictly methods, they can complement the use of static methods in a class.

class Configuration {
    static readonly API_URL: string = "https://api.example.com";
}

console.log(Configuration.API_URL); // Output: https://api.example.com