Constructors
| constructor() | |
| Parameter properties | |
| Initialize safely | |
| Require with strictPropertyInitialization |
constructor()
The constructor runs once when an object is created with new. Use it to store the starting values of fields.
Assign every declared field inside the constructor so no field stays empty by accident.
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Ada");
Parameter properties
A modifier on a constructor parameter declares and assigns a field in one step. It removes the manual field declaration and the manual assignment.
class User {
constructor(public name: string, private age: number = 0) {}
}
const user = new User("Ada", 36);
Initialize safely
Combine default values with optional parameters for flexible construction. Keep the fallback logic in one place so every object starts complete.
class Config {
host: string = "localhost";
port: number = 8080;
constructor(host?: string) {
if (host !== undefined) {
this.host = host;
}
}
}
Require with strictPropertyInitialization
With strict mode on, every field must get a value from an initializer or from the constructor. The compiler stops the build when a field could stay empty.
The fix below is the common pattern: initialize the field where it is declared.
class User {
name: string = "Guest";
}
const user = new User();
console.log(user.name);
Next: Modifiers
Article author: Arthur Isaev