static Keyword in Typescript

Do you want to know about the Typescript static keyword? In this Typescript tutorial, I will explain to you how to use the static keyword in Typescript with a few real examples.

The static keyword in TypeScript is used to define properties and methods on a class itself, rather than on instances of the class. This allows for shared functionality and data across all instances, making it ideal for utility functions, constants, or implementing singleton patterns. Static members are accessed directly using the class name, providing a structured and efficient way to handle class-level operations.

What is the ‘Static’ Keyword in Typescript?

In TypeScript, the static keyword is used to define properties or methods on a class that can be accessed directly on the class itself, rather than on instances of the class. This means that static members are shared across all instances of a class.

Why Use Static in Typescript?

Static members are particularly useful for utility functions or constants that are relevant to all instances of a class but don’t rely on instance-specific data. They can also serve as a way to create singleton-like structures in TypeScript.

How to use static Keyword in Typescript?

Now, let us see some practical examples of how to use the static keyword in Typescript.

Example 1: Constants and Utility Functions

Imagine you are developing an e-commerce application using Typescript as a language, and you need a class to handle currency formatting. You can use a static method in Typescript to define a common utility function. Here is the complete code:

class CurrencyFormatter {
    static readonly DEFAULT_CURRENCY = 'USD';

    static format(amount: number, currency: string = CurrencyFormatter.DEFAULT_CURRENCY): string {
        // Implementation for formatting the currency
        return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount);
    }
}

// Usage
console.log(CurrencyFormatter.format(100));
console.log(CurrencyFormatter.format(100, 'EUR'));

In this example, DEFAULT_CURRENCY is a static property that holds the default currency, and format is a static method that formats a given amount into the specified currency.

Output:

You can see the output in the screenshot below after I ran the code using Visual Studio code.

$100.00
€100.00
static keyword in typescript

Example 2: Singleton Pattern

Singleton is a design pattern that ensures a class has only one instance while providing a global access point to this instance. The static keyword plays a crucial role in implementing this pattern in TypeScript.

Here is the complete code:

class AppSettings {
    private static instance: AppSettings;
    public readonly theme: string;

    private constructor(theme: string) {
        this.theme = theme;
    }

    static getInstance(theme: string = 'light'): AppSettings {
        if (!AppSettings.instance) {
            AppSettings.instance = new AppSettings(theme);
        }
        return AppSettings.instance;
    }
}

// Usage
const settings = AppSettings.getInstance('dark');
console.log(settings.theme); // dark

const sameSettings = AppSettings.getInstance();
console.log(sameSettings.theme);

Here, the AppSettings class ensures that only one instance is created. The getInstance method is static and provides a global access point to the instance.

Example 3: Factory Methods

Static methods can also be used as factory methods to create instances of a class in Typescript. This is particularly useful when you have complex logic for creating an object. Here is the complete code:

class User {
    private constructor(public username: string, public age: number) {}

    static createUser(username: string, age: number): User {
        // Additional logic can be added here
        return new User(username, age);
    }
}

// Usage
const user = User.createUser('john_doe', 30);
console.log(user.username);

In this case, createUser() is a static method that encapsulates the logic for creating User instances.

Check out the output in the screenshot below after I ran the code using VS code.

typescript static keyword

Conclusion

The static keyword in TypeScript offers a structured approach to defining class-level properties and methods. By leveraging static members, developers can create more organized, maintainable, and efficient code, especially in large-scale applications. In this tutorial, we understand how to work with the static keyword in Typescript with some real examples.

You may also like:

>