Open In App

How to define Singleton in TypeScript?

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the Singleton in TypeScript. A singleton is a class that always has only one instance of it at the global level. If more than one instance is created then they all will refer to the same instance and changes in the properties of one instance will reflect in the properties of all the instances.

Let us now see how we can create a singleton in TypeScript.

Approach

  • A singleton is defined using the class keyword with some methods and properties.
  • Define a static variable instance using the static keyword that is of singleton or null type.
  • Now, declare a static function method using the static keyword that is used to check whether the instance of the singleton class is already created or not. If it finds that the instance is created already, then it assigns the same instance to the new request of creating the instance. Otherwise, it creates a new instance and assigns it to the very first request.

Example 1: The below example will show you how you can create a simple singleton in TypeScript.

Javascript




class DemoSingleton {
    private static myInstance:
        DemoSingleton | null = null;
    private constructor() {
    }
 
    static getSingletonInstance():
        DemoSingleton {
        if (!DemoSingleton.myInstance) {
            DemoSingleton.myInstance =
                new DemoSingleton();
        }
        return DemoSingleton.myInstance;
    }
}
 
// It will create a new instance of
// singleton and assign it to instance1
const instance1 = DemoSingleton.
    getSingletonInstance();
 
// It assigns the already created
// instance to instance2
const instance2 = DemoSingleton.
    getSingletonInstance();
 
 
// true, both instances refer
// to the same object
console.log(instance1 === instance2);


Output:

true

Example 2: The below example explains how the properties can be changed for multiple instances that refers to the same object.

Javascript




class DemoSingleton {
    private static myInstance:
        DemoSingleton | null = null;
 
    public name: string = "";
 
    private constructor() {
    }
 
    static getSingletonInstance():
        DemoSingleton {
        if (!DemoSingleton.myInstance) {
            DemoSingleton.myInstance = new DemoSingleton();
        }
        return DemoSingleton.myInstance;
    }
 
    public printMessage(name: string): void {
        this.name = name;
        console.log(`Name: ${name}`);
    }
}
 
// It will create a new instance of
// singleton and assign it to instance1
const instance1 = DemoSingleton.
    getSingletonInstance();
 
// It assigns the already created
// instance to instance2
const instance2 = DemoSingleton.
    getSingletonInstance();
 
// Here instance1 and instance2 both
// refers to the same object
 
// It assigns the same value to name
// property of both instances
instance1.name = "GeeksforGeeks";
console.log(instance1.name, instance2.name);
 
// It updates the name property of
// both the instances
instance2.name = "Google";
console.log(instance1.name, instance2.name);
 
// true, both instances refer to the same object
console.log(instance1.name === instance2.name);


Output:

GeeksforGeeks,  GeeksforGeeks
Google, Google
true


Similar Reads

How to define an array of different generic types in TypeScript ?
In typescript, an array is a data type that can store multiple values of different data types sequentially. Similar to JavaScript, Typescript supports array declaration and there are multiple ways to do it. Declaring and Initializing Arrays: We can either use var or let for declaring an array.The difference is var is used if we want the variable to
4 min read
How to Define Static Property in TypeScript Interface ?
A static property in a class is a property that belongs to the class itself, rather than to instances of the class. It is shared among all instances of the class and can be accessed without creating an instance of the class. Static properties are defined using the static keyword in front of the property. In TypeScript, you can't directly define sta
2 min read
How to Define Interfaces for Nested Objects in TypeScript ?
In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern. Here are step-by-step instructions on how to define interfaces for nested objects in TypeScript:Step 1: Identify the Nested Structures Det
2 min read
How to Define Strongly Type Nested Object Keys with Generics in TypeScript ?
We will look into the effective use of generics in TypeScript to ensure type safety when working with nested objects. By employing generics, developers can establish strongly typed keys for nested objects, significantly reducing the likelihood of runtime errors and enhancing code maintainability. Table of Content Using Recursive GenericsUsing Condi
2 min read
How to Define a Regex-Matched String Type in TypeScript ?
In TypeScript, you can define a type that represents a string matching a specific regular expression using different approaches. Below are the approaches used to define a regex-matched string type in Typescript: Table of Content Template Literal Types with BrandingType Assertion with FunctionTemplate Literal Types OnlyUsing Regular Expression Objec
4 min read
How to Define Type for Array With Unique Items in TypeScript ?
In this article, we will learn how we can define a type for an array with unique items in TypeScript. Below are the possible approaches: Table of Content Using SetUsing GenericsUsing MapUsing TypeScript's Unique Type Feature1. Using SetIn this approach, we have a TypeScript type named uniqueArr which is defined as 'Set<string>'. This ensures
3 min read
How to Define a Generic Type for an Array in TypeScript ?
Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array. Table of Content Using the Type AliasUsing Array Generic TypeU
3 min read
How to Define Generic Type for Matching Object Property Types in TypeScript ?
In Typescript, efficiently managing object property types is essential for type safety and code maintainability. Several techniques can be used to define generic types that match the properties of the objects as listed and explained below. Table of Content Using Record Utility TypeUsing Mappped TypesUsing Partial utility typeUsing intersection Oper
4 min read
How to Define a List of Optional Keys for Typescript Record ?
A Record is a utility type used to define objects with specific key-value pairs. In this article, we will explore two approaches to Define a list of optional keys for Typescript Record. Table of Content Using Partial for Optional KeysUsing conditional types with keyof and PartialUsing Dynamic Key Assignment with Intersection TypesUsing Partial<T
3 min read
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript. There are many methods of declaring an array of ob
6 min read