← Back to TypeScript Course | Chapter 6: Classes | Lesson 2 of 9

Constructor

A constructor is a special method that runs automatically when an object is created with new. It is commonly used to initialize class properties with values supplied by the caller.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
class Account {
  balance: number;
  constructor(initialBalance: number) {
    this.balance = initialBalance; // valid state from the start
  }
}
console.log(new Account(100).balance);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.