I have a specific object that I use to store data received from an API. This object is structured as follows:
class Storage {
isReady: boolean = false;
content: object || null = null;
}
I have noticed that when isReady
is false, content
is null
. Conversely, when isReady
is true, content
is an object
. How can I efficiently define the types for this scenario?
One approach could be creating a function from isReady
to verify if content
is null
. While this is a viable option, it may not work well with dynamic objects.
Another alternative is:
const storage = new Storage() as ({isReady: false, content:null} | {isReady: true, content: object});
However, this method can be cumbersome, especially for larger objects.
I am seeking a solution like the following:
class Storage {
_isReady: boolean = false;
content: object | null = null;
get isReady(): typeof this.content is object {
return this_isReady();
}
Any suggestions would be greatly appreciated.
EDIT: Just to clarify my question a bit further. I am trying to address this issue:
class Storage {
isReady: boolean = false;
content: {property:string} || null = null;
load = () => {
this.content = {property: "value"};
this.isReady = true;
}
}
let storage = new Storage();
storage.load();
if (storage.isReady) {
console.log(storage.content.property); // TypeScript raises an error, assuming that storage.content can be null
}