I'm wondering if there's a way to work around type definitions. Let me provide an example to clarify my question.
Suppose I want to define a type that consists of a large object containing multiple objects:
type BigObject = {
dom: HTMLElement,
count: number
}
This object is defined within a constructor of a class, but by a function called inside the constructor:
class Starter {
bigObject: BigObject;
constructor() {
// A lot of code here, so I can't add more clutter
this.initialize();
}
initialize() {
this.bigObject.dom = document.getElementByID("app");
this.bigObject.count = 0;
}
}
Initially, when I define the properties in the constructor, everything works fine. But when I define them in the initialize function (even though it's called in the constructor), TypeScript informs me that the object has no initializer...
Furthermore, this object will carry important data throughout my application and I'd like to use it in other places. I prefer not to define its properties as possibly undefined (with a question mark) because I perform many checks with exceptions and I am confident that its properties are defined when I use it. Additionally, since I'll be using it frequently, I want to avoid checking if bigObject.dom
is defined every time I access it.
So, when I use question marks, the definition of the object is correct in the Starter
class but I need to check it each time I use it. When I don't use question marks, I don't have to verify its properties but the definition fails.
Can anyone offer some guidance on this issue?
I attempted to provide a basic example of my situation, but in reality, it pertains to a game engine. In this context, the "BigObject" represents an object with services that are distributed across the app. And by "when I use it," I mean when the game engine is running and the services' definitions have been verified.