metodos-variables-estaticos-en-typescript

Static Methods and Variables in TypeScript

  • 3 min

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, and not to individual instances.

If you want to learn more, check out the Object-Oriented Programming Course

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
Copied!

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
Copied!

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 needing 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.
Copied!

Common Use Cases