Sub topic 12
Static members and private constructors
This chapter assumes you know how to declare classes, fields, constructors and methods, and how public, private and protected work on instance members. It covers members that belong to the class itself, and constructors that outside code is not allowed to call.
What static means
A static member belongs to the class, not to its instances. At runtime a class is a constructor function, and static members are properties on that function. You reach them through the class name, and instances do not have them.
class IdGenerator {
static readonly PREFIX = "id-";
private static next = 1;
static create(): string {
return `${IdGenerator.PREFIX}${IdGenerator.next++}`;
}
}
console.log(IdGenerator.create()); // id-1
console.log(IdGenerator.create()); // id-2
// new IdGenerator().create(); // Error: Property 'create' does not exist on type 'IdGenerator'.
// IdGenerator.next; // Error: Property 'next' is private and only accessible within class 'IdGenerator'.Access modifiers and readonly work on static members the same way they do on instance members. A private static field can be read and written by any code inside the class body, including instance methods, but not by outside code.
Static fields, methods, and blocks
Static fields are initialized once, when the class definition is evaluated. If setup needs more than one expression, use a static block (TypeScript 4.4 and later). It runs once, in order with the static field initializers, and can use try/catch and local variables.
class Registry {
static readonly handlers = new Map<string, () => string>();
static {
Registry.handlers.set("ping", () => "pong");
Registry.handlers.set("time", () => "noon");
}
static run(name: string): string {
const handler = Registry.handlers.get(name);
return handler ? handler() : "unknown";
}
}
console.log(Registry.run("ping")); // pong
console.log(Registry.run("nope")); // unknownTwo restrictions apply:
- Static members cannot use the class's type parameters. In
class Box<T>, astaticmember cannot mentionT, because there is one class object shared by everyBox<...>instantiation. - A static member cannot be named
name,lengthorcaller, because those collide with built-in properties of functions. TypeScript reports an error for these.
Static members and inheritance
Subclasses inherit static members: Derived.__proto__ is Base. Inside a static method, this is whatever the method was called on, so it can be the subclass. That behavior leads to a common bug with shared mutable state.
class Base {
static count = 0;
static increment(): number {
return ++this.count;
}
}
class Derived extends Base {}
Base.increment();
Derived.increment();
console.log(Base.count, Derived.count); // 1 2Derived.increment() reads count through the prototype chain and gets 1. The write then creates a new own property on Derived, so the two counters are separate from that point on. If you want one shared counter, write Base.count++ explicitly. If you want a counter per subclass, initialize it in each subclass. Do not mix the two by accident.
Private constructors
Marking a constructor private means only code inside the class body can write new ClassName(...). Outside code must go through a static method that you provide. This gives you two common patterns.
Singleton
class Config {
private static instance: Config | undefined;
private constructor(public readonly env: string) {}
static getInstance(): Config {
Config.instance ??= new Config("dev");
return Config.instance;
}
}
const a = Config.getInstance();
const b = Config.getInstance();
console.log(a === b); // true
// new Config("prod"); // Error: Constructor of class 'Config' is private and only accessible within the class declaration.Factory with validation
A constructor always returns an instance, so it cannot report failure except by throwing. A private constructor plus a static factory lets you return a result type instead, and guarantees that every instance has passed validation.
class Email {
private constructor(public readonly value: string) {}
static parse(input: string): Email | null {
const ok = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(input);
return ok ? new Email(input.toLowerCase()) : null;
}
}
const good = Email.parse("[email protected]");
const bad = Email.parse("not-an-email");
console.log(good?.value); // [email protected]
console.log(bad); // nullSince Email has no public way to build an invalid value, any function that accepts an Email can skip re-checking the string.
Protected and private constructors compared
| Constructor | `new` outside the class | `extends` the class | Typical use |
|---|---|---|---|
| public (default) | allowed | allowed | ordinary classes |
| protected | error | allowed | base classes that only subclasses may instantiate |
| private | error | error | singletons, factories, static-only utility classes |
A class with a private constructor cannot be extended, because the subclass constructor must call super(...). TypeScript reports "Cannot extend a class 'Config'. Class constructor is marked as private."
Gotchas
- Static state is global state. Anything stored in a static field is shared across the whole program, which makes tests order-dependent unless you add a reset method.
- Singletons hide dependencies. Code that calls
Config.getInstance()internally is harder to test than code that receives aConfigas a parameter. Prefer passing instances when you can. - Static-only classes are often unnecessary. A class with only static members and a private constructor behaves like a namespace. In TypeScript, a module with exported functions does the same job with less ceremony.
thisin static methods depends on the call site.const f = Base.increment; f()losesthisand throws at runtime, as with any detached method.
Exercise
A class Pool has a private constructor and a static method create() that calls new Pool(). A teammate writes class SmallPool extends Pool {}. What happens, and how would you change Pool so that subclasses are allowed but new Pool() is still blocked outside the class hierarchy?
Show answer
The extends line is a compile-time error: "Cannot extend a class 'Pool'. Class constructor is marked as private." Change the constructor to protected. Then new Pool() outside the class and its subclasses is still an error, and SmallPool can extend Pool and call super(). Note that Pool.create() can still call new Pool() because it is inside the class body.
Exercise
Given class Base { static count = 0; static increment() { return ++this.count; } } and class Derived extends Base {}, what do Base.count and Derived.count print after calling Base.increment() once and then Derived.increment() twice?
Show answer
Base.count is 1 and Derived.count is 2... wait, count the calls: the first Derived.increment() reads the inherited 1 and creates Derived.count = 2, and the second makes it 3. The output is 1 3.