DEV Community

NETIC
NETIC

Posted on • Updated on

Singleton and Constant in TypeScript

ASAP Understanding

  • A Singleton restricts the instantiation of a class to a single instance and provides a global point of access to that instance,
  • A constant is a value that cannot be changed once it is defined.

Example of a Singleton class

class Singleton {
  private static instance: Singleton;
  private constructor() {}

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

Example of a constant

const PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)