Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to add TypeScript in Next.js ?
Next article icon

How to define Singleton in TypeScript?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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

Next Article
How to add TypeScript in Next.js ?

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to add TypeScript in Next.js ?
    In this article, we will learn how to add TypeScript in Next.js. Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in
    5 min read
  • How to declare nullable type in TypeScript ?
    In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
    2 min read
  • How to declare a module in TypeScript ?
    A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature. Will the code not work without Modules? Of course,
    8 min read
  • How to Convert a String to enum in TypeScript?
    In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript. These are the two approaches that can be used to solve it: Table of Content
    5 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 prop
    3 min read
  • How to fix "object is possibly null" in TypeScript ?
    The "object is possibly null" error in TypeScript occurs when the compiler detects a potential null or undefined value for an object or variable. This error is important for ensuring type safety and preventing runtime errors related to null or undefined values. There are several approaches to fix th
    4 min read
  • How to Use Extension Methods in TypeScript ?
    Typescript developers in general face situations where they need to add functionality to existing classes. The extension method in typescript helps in extending the functionality of predefined classes or third-party libraries without modifying the source code. In Simple words, Extension methods in T
    3 min read
  • How to implement sleep function in TypeScript?
    In TypeScript, a sleep function delays code execution for a specified duration. It can be implemented using setTimeout with async and await, pausing execution within asynchronous functions to wait for a certain time before continuing, which is useful for managing application timing. Syntaxasync func
    2 min read
  • How to install TypeScript ?
    TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
    3 min read
  • How to Use NextJS in Typescript?
    TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences