TypeScript Constructors

Introduction

In this chapter, we will explore constructors in TypeScript. Constructors are special methods in a class that are called when an object of the class is instantiated. They are used to initialize the properties of the object. Understanding how to use constructors is essential for setting up objects in TypeScript.

Table of Contents

  • Definition
  • Constructor Syntax
  • Basic Constructor
  • Parameterized Constructor
  • Default Values in Constructors
  • Overloading Constructors
  • Complete Example with Output
  • Conclusion

Definition

A constructor is a special method in a class that gets called when an object of the class is created. It is used to initialize the object's properties and allocate resources if necessary.

Constructor Syntax

Syntax

class ClassName {
  constructor(parameters) {
    // initialize properties
  }
}

Example

This example demonstrates a simple constructor that initializes properties.

class Person {
  name: string;
  age: number;

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

let person = new Person("Ramesh", 25);
console.log(person);

Output

{ name: 'Ramesh', age: 25 }

Basic Constructor

A basic constructor is used to initialize the properties of an object when it is created.

Example

This example demonstrates a class with a basic constructor that initializes the model and year properties.

class Car {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  display(): string {
    return `This car is a ${this.model} from ${this.year}.`;
  }
}

let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.

Output

This car is a Toyota from 2020.

Parameterized Constructor

A parameterized constructor accepts parameters to initialize the properties of an object.

Example

This example demonstrates a parameterized constructor that initializes the title and author properties of a Book class.

class Book {
  title: string;
  author: string;

  constructor(title: string, author: string) {
    this.title = title;
    this.author = author;
  }

  getSummary(): string {
    return `${this.title} is written by ${this.author}.`;
  }
}

let book = new Book("TypeScript Basics", "John Doe");
console.log(book.getSummary()); // Output: TypeScript Basics is written by John Doe.

Output

TypeScript Basics is written by John Doe.

Default Values in Constructors

Constructors can have parameters with default values, allowing for more flexible object creation.

Example

This example demonstrates a constructor with a default value for the department parameter.

class Employee {
  name: string;
  department: string;

  constructor(name: string, department: string = "General") {
    this.name = name;
    this.department = department;
  }

  getDetails(): string {
    return `Name: ${this.name}, Department: ${this.department}`;
  }
}

let employee1 = new Employee("Suresh", "HR");
let employee2 = new Employee("Ramesh");
console.log(employee1.getDetails()); // Output: Name: Suresh, Department: HR
console.log(employee2.getDetails()); // Output: Name: Ramesh, Department: General

Output

Name: Suresh, Department: HR
Name: Ramesh, Department: General

Overloading Constructors

TypeScript does not support multiple constructors directly. However, you can achieve constructor overloading by using optional parameters or using union types.

Example

This example demonstrates constructor overloading using optional parameters.

class Point {
  x: number;
  y: number;

  constructor(x: number, y?: number) {
    this.x = x;
    this.y = y !== undefined ? y : x; // if y is not provided, use x as the value for y
  }

  display(): string {
    return `Point(${this.x}, ${this.y})`;
  }
}

let point1 = new Point(5);
let point2 = new Point(3, 4);
console.log(point1.display()); // Output: Point(5, 5)
console.log(point2.display()); // Output: Point(3, 4)

Output

Point(5, 5)
Point(3, 4)

Complete Example with Output

In this section, we will combine the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.

TypeScript Code

You can test the following code in the TypeScript Playground:

// Basic Constructor
class Person {
  name: string;
  age: number;

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

let person = new Person("Ramesh", 25);
console.log(person); // Output: { name: 'Ramesh', age: 25 }

// Parameterized Constructor
class Car {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  display(): string {
    return `This car is a ${this.model} from ${this.year}.`;
  }
}

let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.

// Default Values in Constructors
class Employee {
  name: string;
  department: string;

  constructor(name: string, department: string = "General") {
    this.name = name;
    this.department = department;
  }

  getDetails(): string {
    return `Name: ${this.name}, Department: ${this.department}`;
  }
}

let employee1 = new Employee("Suresh", "HR");
let employee2 = new Employee("Ramesh");
console.log(employee1.getDetails()); // Output: Name: Suresh, Department: HR
console.log(employee2.getDetails()); // Output: Name: Ramesh, Department: General

// Overloading Constructors
class Point {
  x: number;
  y: number;

  constructor(x: number, y?: number) {
    this.x = x;
    this.y = y !== undefined ? y : x; // if y is not provided, use x as the value for y
  }

  display(): string {
    return `Point(${this.x}, ${this.y})`;
  }
}

let point1 = new Point(5);
let point2 = new Point(3, 4);
console.log(point1.display()); // Output: Point(5, 5)
console.log(point2.display()); // Output: Point(3, 4)

Conclusion

In this chapter, we covered constructors in TypeScript, including basic constructors, parameterized constructors, default values in constructors, and overloading constructors. We provided a complete example with its output to illustrate how these concepts work in TypeScript. Understanding constructors is essential for initializing objects and setting up their properties in TypeScript programs.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare