Saturday 17 February 2024

What is Constructor Typescript ?067

 What is Constructor Typescript ?

In TypeScript, a constructor is a special method inside a class that is called automatically when you create a new instance of the class using the new keyword. Its primary purpose is to initialize the object's properties and perform any necessary setup during object creation.

Key characteristics of constructors:

  • Name: Must match the class name.

  • No return type: Constructors do not explicitly return a value, but they can implicitly return void.

  • Parameters: Can accept arguments to provide initial values for object properties.

  • Access modifiers: Can be public (accessible from anywhere), private (accessible only within the class), or protected (accessible within the class and subclasses).



class Person {
  name: string;

  constructor(name: string) { = name;

  greet() {
    console.log(`Hello, my name is ${}!`);

const alice = new Person("Alice");
alice.greet(); // Output: "Hello, my name is Alice!"

Constructor Overloading:

TypeScript allows multiple constructors with different parameter lists for a single class, providing flexibility in object creation.


class Point {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;

  constructor(x: number) {
    this.x = x;
    this.y = 0;

const point1 = new Point(3, 4);
const point2 = new Point(5);

Advanced uses:

  • Optional parameters: Make some constructor parameters optional using the ? suffix.

  • Default parameter values: Provide default values for optional parameters.

  • Constructor chaining: Call another constructor from within a constructor using super().


  • You can only have one public constructor, but multiple private or protected constructors are allowed.

  • Constructors are essential for initializing object state and ensuring proper object creation.

By understanding constructors and their capabilities, you can write well-structured and maintainable classes in your TypeScript projects.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.