I have a bunch of typescript types which use a shared Inaccessible
interface in place of objects that the user doesn't have access to.
However, oftentimes the types I'm working with are more complicated than the above (nested data from a GQL endpoint) and the components I'm writing only work if the entire object is defined. Since this is fairly common I'd love to be able to write a typeguard which I could use in any component and would recursively "remove" all Inaccessible
types from all descendants of the base type.
Here is an example of what I'm trying to do. But crucially the AllPropertiesAccessible<T>
type would be generic so it would work with other types with Inaccessible descendants.
interface Inaccessible {
invalidId: string;
}
interface Person {
id: string;
name: string;
}
interface Node {
children: Array<Node | Inaccessible>;
user: Person | Inaccessible;
spouse: Person | Inaccessible;
}
interface FamilyTree {
rootNode: Node | Inaccessible;
}
function isFamilyTreeAccessible(familyTree: FamilyTree) familyTree is AllPropertiesAccessible<FamilyTree> {
// logic which recursively validates that all elements in the tree are accessible
}
function FamilyTreeOrInaccessibleDisplay({familyTree}: {familyTree: FamilyTree}): JSX.Element {
if (isFamilyTreeAccessible(familyTree)) {
return <FamilyTreeDisplay familyTree={familyTree} />
} else {
return <NotAccessibleMessage />
}
}
function FamilyTreeDisplay({familyTree}: {familyTree: AllPropertiesAccessible<FamilyTree>}) {}
function NotAccessibleMessage() {
return <div>Inaccessible</div>
In this example we have a FamilyTree
type which has a bunch of descendants that could be inaccessible. The AllPropertiesAccessible<FamilyTree>
type would be equivalent to:
interface AccessibleNode {
children: Array<AccessibleNode>;
user: Person;
spouse: Person;
}
interface AccessibleFamilyTree {
rootNode: AccessibleNode;
}
Is there a way to write such a AllPropertiesAccessible
type in typescript?