Sub topic 12
Static Members and Private Constructors
Assume you know basic TypeScript types, classes, constructors, and the this keyword. This chapter shows how to attach data and behavior to a class itself instead of to each object. It also shows how a private constructor can control object creation.
Static members belong to the class
A static member belongs to the class object, not to instances created with new. Access it through the class name:
class MathTools {
static readonly pi = 3.14159;
static square(value: number): number {
return value * value;
}
}
console.log(MathTools.pi); // 3.14159
console.log(MathTools.square(5)); // 25You cannot access pi or square through an instance. Inside a static method, use the class name or this to access static members. An instance method can access instance members, but it can also access static members through the class name.
Common uses include:
- Constants shared by every instance.
- Factory methods that create instances.
- Counters or registries shared by all instances.
- Utility methods that do not need object state.
| Member kind | Access form | Has separate value per instance? |
|---|---|---|
| Instance field | `object.value` | Yes |
| Static field | `ClassName.value` | No |
Private constructors control creation
A private constructor prevents code outside the class from calling new. The class can still create instances from a static method. This pattern is useful when construction needs validation or when callers should use a named operation.
class Session {
private static nextId = 1;
readonly id: number;
private constructor(public readonly user: string) {
this.id = Session.nextId++;
}
static create(user: string): Session {
const trimmedUser = user.trim();
if (trimmedUser.length === 0) {
throw new Error("User name cannot be empty");
}
return new Session(trimmedUser);
}
}
const first = Session.create("Ada");
const second = Session.create("Lin");
console.log(first.id, first.user); // 1 Ada
console.log(second.id, second.user); // 2 Lin
// const invalid = new Session("Grace");
// Error: Constructor of class 'Session' is private and only accessible within the class declaration.The static nextId field is shared by every session. The constructor increments it whenever the class creates an object. The create method provides one controlled entry point and guarantees that empty names are rejected.
Choosing this pattern
Use a normal public constructor when callers can safely create objects directly. Use a private constructor with static factory methods when creation requires validation, different creation modes, caching, or a meaningful method name.
Exercise
Why can code call Session.create("Ada") but not new Session("Ada")?
Show answer
create is a public static method, so callers can access it through the class. The constructor is private, so only code inside Session can call it.