Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain methods are called before initialization.
I also need to ensure that some methods can be called before the initialization process. Should I consider switching from an object to a class constructor following the singleton pattern? But then, how do I handle external dependencies for the constructor props?
Any suggestions on how I can improve this structure would be greatly appreciated.
interface StuffType {
x?: string;
y?: string;
z?: string;
fn?: () => void;
isInit: boolean;
}
const _stuff: StuffType = {
x: undefined,
y: undefined,
z: undefined,
fn: undefined,
isInit: false,
};
const isReady = () => _stuff.isInit;
const init = (x: string, y: string, z: string, fn: () => void) => {
if(_stuff.isInit) return;
_stuff.x = x;
_stuff.y = y;
_stuff.z = z;
_stuff.fn = fn;
};
const method1 = () => {
// depends on xyz, fn being defined
if (!_stuff.isInit) throw new Error('not init');
_stuff.fn!();
_stuff.x!;
_stuff.y!;
_stuff.z!;
};
// All the following methods would depend on init being done
// would require check on init/throw error/bang operator on props
// const method3 = () =>
// const method4 = () =>
// const method5 = () =>
// const method6 = () =>
const method2 = () => {
// does not depend on xyz, fn
};
export const Stuff = {
init,
isReady,
method1,
method2,
//etc...
};
Stuff.method2(); // fine
Stuff.method1(); // throws here
Stuff.init('x', 'y', 'z', () => console.log('init'));
Stuff.method1(); // does not throw