Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Constructors

Learn how constructors initialize object properties when an object is created from a TypeScript class.

Simple Explanation: A constructor is a special method inside a class that runs automatically when an object is created using the new keyword. It is commonly used to initialize an object's properties.

1. What is a Constructor?

In TypeScript, the constructor() method is used to initialize an object's properties. It runs automatically when a new instance of the class is created.

A class can have only one constructor implementation. The constructor does not have an explicit return type.

Basic Syntax

class Student {
    name: string;
    age: number;

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

Here, constructor() accepts the student's name and age, then assigns those values to the object's properties using this.

2. Constructor Workflow Diagram

Follow the steps to understand how the constructor initializes properties when a new object is created.

📘
Define Class

Declare the class and its properties.

→
🏗️
Create Object

Call new Student() with arguments.

→
⚙️
Constructor Runs

Constructor assigns the received values.

→
✅
Object Ready

The object is ready to use with initialized data.

Example: When you create new Student("Rahul", 22), the constructor receives "Rahul" and 22 and assigns them to the object.

3. Parameterized Constructor

A parameterized constructor accepts values through parameters. This allows different objects of the same class to store different data.

Example

class Student {
    name: string;
    age: number;

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

    displayInfo(): void {
        console.log("Name: " + this.name);
        console.log("Age: " + this.age);
    }
}

const student1 = new Student("Rahul", 22);
student1.displayInfo();

Expected Output

Name: Rahul
Age: 22

How It Works

📥
Arguments

"Rahul" and 22 are passed while creating the object.

🔄
Assignment

this.name and this.age receive the supplied values.

📤
Display

displayInfo() displays the initialized values.

4. Constructor with Multiple Objects

The same constructor can initialize multiple objects with different values. Each object maintains its own property values.

Example

class Employee {
    name: string;
    salary: number;

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

    displayDetails(): void {
        console.log(this.name + " - " + this.salary);
    }
}

const emp1 = new Employee("Amit", 30000);
const emp2 = new Employee("Priya", 40000);

emp1.displayDetails();
emp2.displayDetails();

Expected Output

Amit - 30000
Priya - 40000

Visual Representation

📘
Employee Class

One class and one constructor definition.

👨‍💼
emp1

Name: Amit

Salary: 30000

👩‍💼
emp2

Name: Priya

Salary: 40000

Both objects use the same constructor, but their property values are different.

5. Constructor with Default Values

Constructor parameters can have default values. If a value is not supplied for a parameter with a default, TypeScript uses its default value.

Example

class Product {
    name: string;
    price: number;

    constructor(name: string = "Pen", price: number = 10) {
        this.name = name;
        this.price = price;
    }

    displayProduct(): void {
        console.log(this.name + " - " + this.price);
    }
}

const product1 = new Product();
const product2 = new Product("Notebook", 50);

product1.displayProduct();
product2.displayProduct();

Expected Output

Pen - 10
Notebook - 50

product1 uses the default values because no arguments were passed. product2 uses the values supplied during object creation.

6. Constructor Parameter Properties

TypeScript provides a shorter syntax called parameter properties. By adding an access modifier such as public to a constructor parameter, TypeScript declares and initializes that class property automatically.

Example

class Student {
    constructor(
        public name: string,
        public age: number
    ) {}

    displayInfo(): void {
        console.log(this.name);
        console.log(this.age);
    }
}

const student1 = new Student("Neha", 23);
student1.displayInfo();

Expected Output

Neha
23
Remember: public name: string automatically creates and initializes the public name property. You do not need to declare name separately or assign it manually inside the constructor.

7. Important Points About Constructors

Point Explanation
Constructor name Use the special name constructor.
Automatic execution Runs when an instance is created with new.
Initialization Can assign initial values to object properties.
Return type Do not specify an explicit return type for a constructor.
Constructor count A class can have one constructor implementation.
Default parameters Can provide default values for constructor parameters.

Summary

A constructor initializes objects when they are created. Parameterized constructors receive values from the caller, default parameters provide fallback values, and parameter properties offer a shorter way to declare and initialize class properties.

Next, learn inheritance and how one class can reuse functionality from another class.