Constructor
In this page:
Defining a Constructor
A constructor is written using the constructor keyword inside a class, and its parameters can be used to set up the object's initial state as soon as new is called, so an object never exists in an unfinished form.
Example: Defining a Constructor
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
console.log(new Person("Dev").name);
Multiple Constructor Parameters
A constructor can receive multiple parameters to initialize several properties at once, and each parameter's type is checked the same way a regular function parameter's type would be.
Example: Multiple Constructor Parameters
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const u = new User("Nina", 25);
console.log(u.name, u.age);
Constructor Defaults
Constructor parameters can have default values, so when the caller does not provide a value for that parameter, TypeScript falls back to the specified default instead of leaving the property undefined.
Example: Constructor Defaults
class Settings {
theme: string;
constructor(theme: string = "light") {
this.theme = theme;
}
}
console.log(new Settings().theme);
Parameter Properties
TypeScript supports parameter properties, which let constructor parameters become class properties automatically just by adding an access modifier like public or private in front of them, removing the need to declare and assign the property separately.
Example: Parameter Properties
class Point {
constructor(public x: number, public y: number) {}
}
const p = new Point(3, 4);
console.log(p.x, p.y);
Constructor Initialization
Constructors matter because an object must start in a valid and meaningful state; initializing required data up front avoids the bugs that come from methods running against a half-constructed object.
Example: Constructor Initialization
class Account {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance; // valid state from the start
}
}
console.log(new Account(100).balance);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: