TypeScript Static Members
A static member belongs to the class itself rather than to any instance. Every instance shares the same static value.
A static counter shared across instances
Each constructor call adds one to the same class-level field. The count grows across instances instead of restarting per instance.
class Session {
static total = 0;
constructor() {
Session.total++;
}
}
new Session();
new Session();
console.log(Session.total);
new Session();
console.log(Session.total);A static factory method creates instances
The factory methods are called on the class itself. Each one builds and returns a ready instance.
class Badge {
private constructor(public label: string) {}
static guest(): Badge {
return new Badge("guest");
}
static staff(unit: string): Badge {
return new Badge("staff-" + unit);
}
}
const guestBadge = Badge.guest();
const staffBadge = Badge.staff("ops");
console.log(guestBadge.label);
console.log(staffBadge.label);Statics are inherited through a subclass
The subclass declares no field of its own. Reading the static through the subclass name shows the base class value.
class Registry {
static entries = 0;
static register(): void {
Registry.entries++;
}
}
class GuestRegistry extends Registry {}
Registry.register();
Registry.register();
console.log(GuestRegistry.entries);
GuestRegistry.register();
console.log(Registry.entries);A static is not on the instance
The instance carries no total field of its own. Reading the static through the instance is refused.
class Session {
static total = 0;
constructor() {
Session.total++;
}
}
const s = new Session();
console.log(s.total);Example
class Ticket {
static issued = 0;
private constructor(public code: string) {}
static next(): Ticket {
Ticket.issued++;
return new Ticket("T-" + Ticket.issued);
}
}
const first = Ticket.next();
const second = Ticket.next();
console.log(first.code);
console.log(second.code);
console.log(Ticket.issued);Key points
- A static member is written with the `static` keyword.
- Code reads a static member through the class name, such as `Session.total`.
- A static field holds one value shared by all instances.
- A static factory method builds and returns an instance of the class.
- A subclass inherits static members and reads the same values through its own name.
- A static member is not part of an instance, and reading it through an instance is refused.
In this example, the static factory next builds each ticket and advances the shared counter. Both tickets carry codes from the same sequence, and the counter ends at two.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
Where does a static field live?