WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Intermediate · question 39 of 100

How do you create a private constructor in TypeScript and why would you want to do it?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, you can create a private constructor by marking the ‘constructor‘ with the ‘private‘ keyword. A class with a private constructor cannot be instantiated from outside the class directly. The main reason for using a private constructor is to apply the Singleton pattern to ensure that a class has only one single instance throughout the lifetime of an application. Here’s an example of a class with a private constructor:

class Singleton {
  private static instance: Singleton;

  private constructor() {
    // Initialization code
  }

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
}

In this example, we have a Singleton class with a private constructor. To create an instance of the Singleton class, we use the static method ‘getInstance()‘. This method checks if an instance of the Singleton class already exists, and if not, it creates a new instance. Since the ‘constructor‘ is private, we cannot instantiate this class using the ‘new‘ keyword outside of the class, which helps ensure that there’s only one instance of the class.

class Singleton {
  private static instance: Singleton;

  private constructor() {
    % Initialization code
  }

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
}

As for why you would want to use a private constructor, the main reasons are:

1. Singleton pattern: To enforce that a class should have only one instance throughout the lifetime of your application (useful for centralized management, like configuration or logging).

2. Factory pattern: To provide a consistent interface or to create instances of different derived classes based on some criteria, without exposing the constructor directly to the users of the class.

3. Preventing misuse of a class: Restricting the instantiation process so that the class can only be instantiated in specific ways, like through static methods or helper classes.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics