Sub topic 3
Constructors and initializing state
This chapter assumes you know basic TypeScript type annotations, how this works in JavaScript functions, and the general idea of a class. It covers how a constructor builds a valid object, the order in which initialization code runs, and the errors that order causes.
What a constructor does
A constructor is a special method named constructor. JavaScript calls it once each time you write new ClassName(...). Its job is to give the new object a valid starting state.
class User {
readonly id: string;
name: string;
active: boolean;
constructor(id: string, name: string, active: boolean = true) {
this.id = id;
this.name = name;
this.active = active;
}
}
const u = new User("u-1", "Ada");
console.log(u.active); // trueConstructor parameters follow the usual function rules. They need type annotations, can be optional (name?: string), can have defaults, and can use rest syntax. Arguments are checked at each new call, so new User("u-1") is a compile-time error.
A few rules are specific to constructors:
- A constructor has no return type annotation. Its return type is always the class instance.
- A class has at most one constructor implementation.
- If you write none, TypeScript supplies an empty one. In a subclass, the implicit constructor passes all its arguments to
super. readonlyfields can be assigned in the constructor, and only there (or in their own initializer).
Validating in the constructor
A constructor can throw. If it does, no instance is created, so the rest of your code never sees an invalid object.
class Percentage {
readonly value: number;
constructor(value: number) {
if (!Number.isFinite(value) || value < 0 || value > 100) {
throw new RangeError(`Percentage out of range: ${value}`);
}
this.value = value;
}
}
console.log(new Percentage(42).value); // 42Keep constructors cheap and synchronous. A constructor cannot be async, and it cannot return a Promise of the instance. If you need asynchronous setup, such as opening a connection, use a static factory method. Those are covered in the chapter on static members.
Overloaded constructors
TypeScript lets you declare several call signatures and then write one implementation that handles all of them. The implementation signature is not visible to callers, so it must be compatible with every overload.
class Duration {
readonly ms: number;
constructor(ms: number);
constructor(minutes: number, seconds: number);
constructor(first: number, second?: number) {
this.ms = second === undefined ? first : (first * 60 + second) * 1000;
}
}
console.log(new Duration(1500).ms); // 1500
console.log(new Duration(2, 30).ms); // 150000
// new Duration(1, 2, 3); // Error: no overload expects 3 argumentsOverloads work, but they make the implementation harder to read. If the overloads mean different things, a static factory such as Duration.fromMinutes(2, 30) is usually clearer.
Initialization order
Several kinds of code can run when you create an object. Their order matters.
For a class with no parent:
- Field initializers run in the order they appear in the class body.
- The constructor body runs.
For a subclass:
- The subclass constructor starts, and arguments are bound.
super(...)runs the parent constructor, following the same two steps for the parent.- When
superreturns, the subclass's own field initializers run. - The rest of the subclass constructor body runs.
function log(message: string): string {
console.log(message);
return message;
}
class Base {
baseField = log("1. Base field initializer");
constructor() {
log("2. Base constructor body");
}
}
class Derived extends Base {
derivedField = log("3. Derived field initializer");
constructor() {
super();
log("4. Derived constructor body");
}
}
new Derived();The messages print in the numbered order.
Rules for super()
A subclass constructor that does anything beyond the implicit default must call super(...) before it uses this. The compiler enforces this:
class Animal {
constructor(public name: string) {}
}
class Dog extends Animal {
constructor(name: string, private tricks: string[]) {
// this.tricks.push("sit"); // Error: 'super' must be called before accessing 'this'
super(name);
}
}A subclass that declares initialized fields or parameter properties must make super(...) a root-level statement. In current TypeScript versions you may run code before super as long as that code does not touch this. For example, you can compute an argument or validate a parameter first.
Gotcha: parent constructors see unfinished subclasses
The parent constructor runs before the subclass's field initializers. If the parent constructor calls a method that a subclass overrides, that method runs on an object whose subclass fields are not yet set.
class Base {
constructor() {
this.describe();
}
describe(): void {
console.log("base");
}
}
class Child extends Base {
private label = "child";
describe(): void {
console.log(this.label);
}
}
new Child(); // undefinedTypeScript does not report an error here, and the type of this.label says string. Avoid calling overridable methods from a constructor. If you must, make the method not depend on subclass state.
Gotcha: field semantics and the compile target
With a target of ES2022 or later, or with useDefineForClassFields enabled, class fields use JavaScript's define semantics. Fields are created with Object.defineProperty when the class is initialized, and a field declared without an initializer is set to undefined. That includes a field that redeclares a property from the parent class, which can silently erase a value the parent constructor assigned.
class Parent {
constructor(public value: number = 5) {}
}
class Kid extends Parent {
declare value: number; // 'declare' redeclares the type without emitting a field
}
console.log(new Kid().value); // 5Without declare, a plain value: number; line in Kid would reset value to undefined under define semantics. When you only want to narrow a parent property's type, use declare.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `'super' must be called before accessing 'this'` | `this` used before `super(...)` | Call `super` first, or move the code after it |
| `Constructors for derived classes must contain a 'super' call` | A subclass constructor never calls `super` | Add `super(...)` |
| `Cannot assign to 'x' because it is a read-only property` | Assigning a `readonly` field outside the constructor | Assign in the constructor or an initializer |
| A field is `undefined` inside the parent constructor | Subclass initializers have not run yet | Do not use subclass state during parent construction |
Exercise
A class Base calls this.setup() in its constructor. A subclass Sub overrides setup() to read this.config, and config is declared in Sub as config = { debug: true };. What does setup() see for this.config when you run new Sub(), and why?
Show answer
It sees undefined. The Base constructor body runs inside super(), before Sub's field initializers. Sub's override of setup() is the method that gets called, but config has not been assigned yet. The fix is to avoid calling overridable methods from the constructor, or to make setup() not depend on Sub's fields.
Exercise
Write a class Range with readonly fields start and end. The constructor should throw an Error if start is greater than end. Which two places can assign a readonly field?
Show answer
class Range { readonly start: number; readonly end: number; constructor(start: number, end: number) { if (start > end) { throw new Error("start must not exceed end"); } this.start = start; this.end = end; } } A readonly field can be assigned in its own initializer or in the constructor of the same class.