Sub topic 3
Constructors and Initializing State
Assume you know basic TypeScript types, JavaScript functions, this, and the purpose of object-oriented programming. This chapter focuses on how a constructor creates a valid object and initializes its state.
A constructor is a special method that runs when you call new. It receives the values needed to create an object and assigns those values to the object's fields. A field is data stored on each instance of a class.
flowchart TD
A["new Order('o-1', 3)"] --> B["Constructor receives arguments"]
B --> C["Fields are initialized"]
C --> D["Constructor validates state"]
D --> E["A usable Order instance is returned"]class Order {
public readonly id: string;
private quantity: number;
constructor(id: string, quantity: number) {
if (quantity < 1) {
throw new RangeError("Quantity must be at least 1");
}
this.id = id;
this.quantity = quantity;
}
getQuantity(): number {
return this.quantity;
}
}
const order = new Order("o-1", 3);
console.log(order.id); // o-1
console.log(order.getQuantity()); // 3The expression new Order("o-1", 3) creates an object and calls its constructor. Inside the constructor, this refers to that new object. Assigning this.id and this.quantity gives the object its initial state.
Initializing every field
When strictPropertyInitialization is enabled, TypeScript checks that each instance field receives a value in its declaration or in every valid constructor path.
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
}This class is valid because the constructor always assigns name. The following class produces an error:
class Session {
private token: string;
constructor(isGuest: boolean) {
if (!isGuest) {
this.token = "authenticated";
}
}
}A guest session can leave token uninitialized. Fix the design by assigning a value on every path, making the field optional, or requiring the value as a constructor argument.
Constructor design choices
A constructor should establish the invariants of an object. An invariant is a rule that should remain true while the object is used. Validation belongs in the constructor when invalid state must never exist.
| Choice | Use it when |
|---|---|
| Required parameter | The object cannot work without the value |
| Default parameter | A sensible value exists for omitted input |
| Validation | Invalid state must be rejected immediately |
| Optional field | The object can meaningfully exist without the value |
TypeScript also supports parameter properties, which declare and initialize fields directly in the constructor signature. They are useful for short classes, but separate assignments can be clearer when validation or transformation is required.
Exercise
Why should the Order constructor validate quantity before assigning it?
Show answer
Validation prevents an Order instance from being created with an invalid quantity, so later methods can rely on that invariant.