Sometimes, we want to define a singleton in TypeScript.
In this article, we’ll look at how to define a singleton in TypeScript.
How to define a singleton in TypeScript?
To define a singleton in TypeScript, we can create a class with a getter to return the singleton instance.
For instance, we write
class MyClass {
private static _instance: MyClass;
private constructor() {
//...
}
public static get Instance() {
return this._instance ?? (this._instance = new this());
}
}
const myClassInstance = MyClass.Instance;
to create the Instance
static getter in the MyClass
class.
We return this._instance
if it’s defined or assign a new MyClass
instance to this._instance
and return it with
this._instance = new this()
Conclusion
To define a singleton in TypeScript, we can create a class with a getter to return the singleton instance.