I often find myself needing to use a singleton based pattern when creating web apps with typescript and react. Previously I have always implemented these with object literals like so:
interface IExample {
var_one: string;
var_two: boolean;
func_one: () => void;
func_two: () => void;
}
const Example:IExample = {
var_one: "",
var_two: false,
func_one() {
return;
},
func_two() {
return;
}
}
I would much prefer to use a class based system but am wondering if there are any downsides to this or what are the pros and cons of each. An example would be:
class ExampleClass
{
private static _instance:ExampleClass = new ExampleClass();
constructor() {
if(ExampleClass._instance){
throw new Error("Instance already created");
}
ExampleClass._instance = this;
}
}
I have previously only really used the object literal pattern in my code but would much prefer to use the class based system if there is little difference between the two.