Exploring Constructors in TypeScript Classes

Understanding Constructors in TypeScript

Welcome to the OOP station! Today, we're going to dive into constructors in TypeScript classes. Constructors play an essential role in creating and initializing objects. Picture a constructor as a blueprint — it details the components necessary for creating each object.

Just like JavaScript, if you don't provide a constructor in your TypeScript class, a default one will be supplied. Imagine this scenario as being given a blank blueprint sheet ready for you to customize!

Constructors in TypeScript

Creating Objects Using Constructors

Let's create our first Car object using the new keyword:

TypeScript
let myCar = new Car("Toyota", "Corolla", "red");
// Prints a message from the constructor:
// Instantiated a Car instance with brand=Toyota, model=Corolla, color=red

myCar is a Car object, representing a red Toyota Corolla. This object has properties defined by the constructor!

Special Properties of Constructors

Although a TypeScript class can host numerous methods, it is bound by one condition — it can only accommodate a single constructor. If we attempt to declare more than one constructor, TypeScript will raise a SyntaxError.

In instances where no explicit constructor is defined, TypeScript provides a default one: constructor() {}.

Furthermore, we can assign default values to parameters as shown below:

class Car {
  brand: string;
  model: string;
  color: string;

  // 'color' has a default value of "white"
  constructor(brand: string, model: string, color: string = "white") {
    this.brand = brand;
    this.model = model;
    this.color = color;
  }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal