In TypeScript, the static
keyword is used to define class members that belong to the class itself rather than to any instance of the class. Static members can include properties and methods that are shared by all instances of the class and can be accessed directly on the class itself without creating an instance.
Static Properties
Static properties are variables that are shared across all instances of a class. They can be accessed directly on the class.
class MyClass {
static staticProperty: string = 'I am a static property';
static logStaticProperty() {
console.log(MyClass.staticProperty);
}
}
// Accessing static property
console.log(MyClass.staticProperty); // Output: I am a static property
Static Methods
Static methods are functions that belong to the class itself rather than any object created from the class. These methods can be called on the class itself.
class Calculation {
static square(x: number): number {
return x * x;
}
static cube(x: number): number {
return x * x * x;
}
}
// Calling static methods
console.log(Calculation.square(5)); // Output: 25
console.log(Calculation.cube(3)); // Output: 27
Static Initialization Blocks
TypeScript supports static initialization blocks, which allow for more complex static member initialization. This feature is part of ECMAScript 2022.
class Config {
static settings: { [key: string]: string } = {};
static {
Config.settings['appName'] = 'MyApp';
Config.settings['version'] = '1.0.0';
}
static getSetting(key: string): string | undefined {
return Config.settings[key];
}
}
// Accessing static settings
console.log(Config.getSetting('appName')); // Output: MyApp
console.log(Config.getSetting('version')); // Output: 1.0.0
Use Cases for Static Members
Utility Functions: Functions that perform operations that do not depend on instance-specific data.
class Utility {
static max(a: number, b: number): number {
return a > b ? a : b;
}
}
console.log(Utility.max(10, 20)); // Output: 20
Constants: Defining constants that are used throughout the application.
class Constants {
static readonly PI: number = 3.14159;
static readonly MAX_USERS: number = 100;
}
console.log(Constants.PI); // Output: 3.14159
console.log(Constants.MAX_USERS); // Output: 100
Configuration and Settings: Storing global configuration or settings.
class AppConfig {
static readonly ENVIRONMENT: string = 'production';
static readonly VERSION: string = '1.0.0';
}
console.log(AppConfig.ENVIRONMENT); // Output: production
console.log(AppConfig.VERSION); // Output: 1.0.0