I have a unique singleton implementation:
class UniqueSingleton {
private static instance: UniqueSingleton;
private constructor() {
// Only allows instantiation within the class
}
public static getInstance(): UniqueSingleton {
if (!UniqueSingleton.instance) {
UniqueSingleton.instance = new UniqueSingleton();
}
return UniqueSingleton.instance;
}
someMethod(): void {
console.log("Singleton method executed");
}
}
Although there is a type InstanceType
, it does not support private constructors.
// Attempting to assign a private constructor type to a public constructor type results in an error
type SingletonType = InstanceType<typeof UniqueSingleton>;
How can a custom type be created to retrieve the instance type of classes with private constructors?
UPDATE
Let me clarify the situation. I am working with a unique singleton class that has a private
constructor. I need to pass this singleton to the constructor of another generic class as a parameter:
class CustomEntity<T extends typeof UniqueSingleton = typeof UniqueSingleton> {
private singletonInstance: InstanceType<T>;
constructor(instance: InstanceType<T>) {
this.singletonInstance = instance;
}
}
Due to the UniqueSingleton
class having a private
constructor, I encounter the error
Cannot assign a 'private' constructor type to a 'public' constructor type
when trying to access its instance InstanceType<T>
. Therefore, I am inquiring if it is feasible to create a custom generic type that supports classes with "private" constructors and returns a similar instance type to "InstanceType"?