In TypeScript, the static keyword is used to define class members (properties or methods) that belong to the class itself, not to individual objects created from the class.
1. Core idea
Without static
Each object gets its own copy.
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
const u1 = new User("Alice");
const u2 = new User("Bob");
name belongs to each instance.
With static
The member belongs to the class, not the instance.
class User {
static role = "USER";
}
User.role; // "USER"
❌ This is not allowed:
const u = new User("Alice");
u.role; // Error
2. Static properties
Static properties are shared across all instances.
class Counter {
static count = 0;
constructor() {
Counter.count++;
}
}
new Counter();
new Counter();
Counter.count; // 2
✔ One shared value
✔ Often used for counters, configuration, constants
3. Static methods
Static methods are called on the class itself.
class MathUtils {
static add(a: number, b: number): number {
return a + b;
}
}
MathUtils.add(2, 3); // 5
Static methods:
Do not use this to refer to instance data
Are utility or helper functions
4. Static vs instance members
class Example {
static staticValue = 10;
instanceValue = 20;
static staticMethod() {
return Example.staticValue;
}
instanceMethod() {
return this.instanceValue;
}
}
Usage:
Example.staticMethod(); // OK
new Example().instanceMethod(); // OK
Example.instanceMethod(); // Error
new Example().staticMethod(); // Error
5. Accessing static members inside the class
Use the class name, not this.
class Logger {
static logCount = 0;
static log(message: string) {
Logger.logCount++;
console.log(message);
}
}
6. Static and access modifiers
Static members can be public, private, or protected.
class Config {
private static apiKey = "secret";
static getApiKey() {
return Config.apiKey;
}
}
7. Static with readonly (constants)
Very common pattern:
class HttpStatus {
static readonly OK = 200;
static readonly NOT_FOUND = 404;
}
Usage:
HttpStatus.OK; // 200
8. Static methods as factories
Static methods are often used to create instances.
class User {
constructor(public name: string) {}
static createGuest() {
return new User("Guest");
}
}
const guest = User.createGuest();
This is called a factory method.
9. Static and inheritance
Static members are inherited, but accessed via the subclass.
class Base {
static type = "base";
}
class Child extends Base {}
Child.type; // "base"
10. When to use static
Use static when:
The data or logic belongs to the class as a whole
You need shared state
Writing utility or helper functions
Defining constants
Creating factory methods
Avoid static when:
The value depends on object state
Each instance needs its own data
Quick summary
static means belongs to the class
Accessed using the class name
Shared across all instances
Works with properties and methods
Common for utilities, constants, counters, factories