I have an object that I need to conditionally render some JSX based on certain properties. I want to restrict access to specific parts of the object until certain conditions are met. Here is my scenario:
const { alpha, bravo } = myObject;
if (alpha.loading === true) {
// At this point, no properties on bravo should be accessible
// this means
// bravo.active must throw an undefined error here
return "Loading"
}
if (alpha.error === true) {
return "Error"
}
// Bravo should only be accessible here
// this means:
// type = {
// signedIn: boolean
//
if(bravo.signedIn === false {
return "Guest"
}
return "Signed In"
Currently, I am using the following type definition for myObject
:
type MyObjectType = {
alpha: {
loading: true;
}
} | {
alpha: {
loading: false;
error: true;
}
} | {
alpha: {
loading: false;
error: false;
}
bravo: {
signedIn: false
}
} | {
alpha: {
loading: false;
error: false;
}
bravo: {
signedIn: true;
name: string;
}
}
TypeScript throws an error saying
Property 'signedIn' does not exist on type MyObjectType
. How can I destructure this property along with auth
but ensure that none of its properties are accessible before auth.loading === false
and auth.error == false
? The same applies to bravo.name
, which should only be available when bravo.signedIn === true
. Any assistance on this matter would be greatly appreciated.
Thank you in advance for your help!