Exploring TypeScript Classes: Constructors and Class Methods

Topic Overview

Welcome to an exciting exploration of TypeScript classes, where we delve into constructors and class methods. Imagine building a robot: Constructors establish its initial state, and class methods instruct it to perform tasks. Ready to deepen your understanding? Let’s get started!

Revisiting TypeScript Classes

A TypeScript class serves as a blueprint for creating objects and incorporates static typing for both properties and methods. Here's a basic class, Robot, with type annotations:

class Robot {
    // Class definition
}

const robotInstance = new Robot();

Initially, this Robot class is an empty shell. To make it functional, we need to define properties with explicit types, as well as methods.

Deep Dive into Constructors

A constructor is a unique method in TypeScript that sets up an object when an instance is created. You'll use the constructor keyword to define it, and it is automatically invoked during the instance creation process. If no constructor is explicitly defined, TypeScript provides a default constructor, allowing instance creation without initializing specific properties. By using static typing within the constructor, as shown in the code block, you ensure that the parameters have specified types, which aids in maintaining consistency and reducing errors when initializing object properties.

Here, we enhance the Robot class by adding a constructor:

class Robot {
    name: string;
    color: string;

    constructor(name: string, color: string) {
        this.name = name;
        this.color = color;
    }
}

const robotInstance = new Robot("Robbie", "red");

In this case, the constructor method gets automatically called when we create a new Robot instance, set with name and color attributes. When creating an instance of Robot, the constructor initializes properties in the order they are defined in the constructor.

Multiple Constructors with Default Parameters

While TypeScript does not support multiple constructors, you can attain flexibility using default parameters, where a parameter is given a default value if no value or undefined is provided. Type annotations play a crucial role here, guaranteeing that parameters have defined types, even when default values are utilized.

Here's a default color for our robots:

class Robot {
    name: string;
    color: string;

    constructor(name: string, color: string = 'grey') {
        this.name = name;
        this.color = color;
    }
}

const robotInstance = new Robot("Robbie", "red");
const robotInstance2 = new Robot("Bobby");

With default parameters, the color becomes optional, defaulting to grey if not provided, maintaining type safety. As a result, the robot instance Bobby is assigned the color grey by default.

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