CodeWithMihir

TypeScript Tutorial

TypeScript Constructors Explained

Learn how constructors work in TypeScript classes, including parameters, property initialization, parameter properties, optional values, and defaults.

Welcome back! I am Mihir, and in this lesson we will learn constructors in TypeScript.

A constructor is a special method that runs when you create a new class instance.


Basic Constructor

class User {
  name: string;

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

const user = new User("Mihir");

The constructor receives name and assigns it to the instance.


Multiple Constructor Parameters

class Product {
  name: string;
  price: number;

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

const product = new Product("Mouse", 1200);

TypeScript checks both arguments.


Constructor Parameter Properties

TypeScript has a shortcut for creating and assigning properties.

class User {
  constructor(public name: string, public email: string) {}
}

This is the same idea as:

class User {
  name: string;
  email: string;

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

The shorter version is common in TypeScript classes.


Default Constructor Values

class Button {
  constructor(public label: string = "Click me") {}
}

const button = new Button();

button.label is:

"Click me"

Optional Constructor Parameters

class Profile {
  constructor(public name: string, public bio?: string) {}
}

const profile = new Profile("Mihir");

bio is optional and has the type:

string | undefined

Calling Methods from Constructors

class Logger {
  constructor(public prefix: string) {
    this.log("Logger started");
  }

  log(message: string) {
    console.log(`[${this.prefix}] ${message}`);
  }
}

This is valid, but keep constructors simple when possible.


Quick Recap

  • Constructors run when creating class instances.
  • Constructor parameters can be typed.
  • Parameter properties create and assign class properties in one step.
  • Constructors can use optional and default parameters.
  • Keep constructors focused on setup.

Next up, we will learn Public Private Protected →.