0

I need help in figuring out how to properly assert a type in typescript.

The code that I'm working with is confusing rn (I think I made it more complicated than it needed to be lol :3) so I will just give you the overview of what I'm trying to accomplish.

So basically I have a ConcreteFactory class that implements the IAbstractFactory interface. The ConcreteFactory class can create/produce 3 different Concrete Classes BaseDocument, DocumentA, and DocumentB.

interface IAbstractFactory{
    createBaseDocument(): Promise<IAbstractDocument>;
    createDocumentA(): Promise<IAbstractDocument>;
    createDocumentB(): Promise<IAbstractDocument>;
}

class ConcreteFactory implements IAbstractFactory{
    public async createBaseDocument(): Promise<IAbstractDocument> {
        return new BaseDocument();
    }

    public async createDocumentA(): Promise<IAbstractDocument> {
        return new DocumentA();
    }

    public async createDocumentB(): Promise<IAbstractDocument> {
        return new DocumentB();
    }
}

Note that only the Document class implements the IAbstractDocument interface. DocumentA and DocumentB both extend BaseDocument.

interface IAbstractDocument{
    methodBase(){};
}

class BaseDocument implements IAbstractDocument{
    methodBase(){};
}

// uses all of BaseDocuments functions but has some extra functions that DocumentB does not have
class DocumentA extends BaseDocument{
    methodBase(){}; 
    methodA(){}; // not implemented in IAbstractDocument, throws error
}

// uses all of BaseDocuments functions but has some extra functions that DocumentA does not have 
class DocumentB extends BaseDocument{
    methodBase(){}; 
    methodB(){}; // not implemented in IAbstractDocument, throws error
}

I also have a class called Tree which will build a Tree, with each node being of type IAbstractDocument

class Tree{
    rootNode:IAbstractDocument; // Realistically of type DocumentA or DocumentB, IAbstractDocument is throwing error, explained below
    
    nodes: IAbstractDocument[]; // Realistically of type DocumentA or DocumentB, IAbstractDocument is throwing error, explained below

    // this function will create factory and the factory will create DocumentA or Document B
    createDocument(){}

    addDocument()

}

My goal is to create a Tree of Documents. The rules are DocumentA can contain children nodes, both of type DocumentA or DocumentB, but DocumentB cannot have any children (they can only be leaf nodes).

The problem is:

Although DocumentA and DocumentB both extend BaseDocument. In the Tree class they are defined under the type IAbstractDocument (I did this because I thought that's what the ConcreteFactory is returning). So now I getting an error that the unique functions in DocumentA and DocumentB(methodA and methodB, respectively) are not defined in IAbstractDocument. So I cannot use them in the Tree class, I can only use methodBase().

My question is:

How do I treat both DocumentA and DocumentB as the same yet different Type? They should both be considered Document Nodes in Tree, but they have different functions related to them.

Any help would be appreciated, thank you!

8
  • Please consider modifying the code here so as to constitute a minimal reproducible example suitable for dropping into a standalone IDE like The TypeScript Playground so that others can reproduce your issue (any errors you are talking about should be evident) and only your issue (other errors like typos or undeclared dependencies should be removed). It's a lot easier to help if I can start working on the answer immediately and not have to work on the question first.
    – jcalz
    Feb 4, 2021 at 16:37
  • I'm not sure what to say about Tree here; shouldn't the nodes be other Tree instances? And if you have such differing requirements for the child/leaf distinction, you probably want Tree itself to be subclassable and have a DocumentATree and a DocumentBTree.
    – jcalz
    Feb 4, 2021 at 16:47
  • I'd be inclined to use union types and avoid the general base/abstract versions. Does this work for you or give you direction? If so I'll write up an answer; if not, please elaborate in your question.
    – jcalz
    Feb 4, 2021 at 16:57
  • Im sorry if I didn't give a reproducible example, I should've thought about that. The Union types do make sense and I think that's the answer I needed. Thank you! But what did you mean by having the nodes be other Tree instances? Is it better for performance to split the Tree into multiple sub Trees? I was trying to recreate the functionality of this Tree traversal Algorithm bfs-dfs-example, except I wanted to replace TreeNode with DocumentA and/or DocumentB.
    – Jared
    Feb 4, 2021 at 18:01
  • Also there's one other thing I wanted to clarify about the two types of Documents. I'm sorry if I didn't explain it well, but DocumentA is acting as a type of "Collection"(DocA) of other "sub-collections"(DocA) or "sub-Items"(DocB). And DocumentB is just acting as an Item, that can exist by itself(root node) or be the child of a "Collection/sub-Collection"(DocA). So an example of the Tree structure could be DocA -> [DocB, DocB] OR DocA -> [DocA, DocA] -> [[DocB, DocB], [DocB, DocB]] OR DocB
    – Jared
    Feb 4, 2021 at 18:17

1 Answer 1

1

I think that you will likely want to use union types to represent "either-or", and not the superclass or other base types, which can't be checked as easily. In general you should probably use as specific a type as necessary to allow the compiler to know what you're doing.

In what followed I will be changing the name DocumentA to DocumentCollection and DocumentB to DocumentSingle since I think that's what your intent is. A DocumentCollection will have a children property, and a DocumentSingle will not. Here's ConcreteFactory:

class ConcreteFactory {
    public async createBaseDocument(): Promise<BaseDocument> {
        return new BaseDocument();
    }

    public async createDocumentCollection(): Promise<DocumentCollection> {
        return new DocumentCollection();
    }

    public async createDocumentSingle(): Promise<DocumentSingle> {
        return new DocumentSingle();
    }
}

See how it returns more specific types in its return signature. Now let's look at possible implementations for your Document classes:

class BaseDocument {
    methodBase() { };
    constructor(public docName: string = "") { }
}

class DocumentCollection extends BaseDocument {
    methodBase() { };
    methodCollection() { console.log("MethodCollection by " + this.docName) };
    children: Array<DocumentCollection> | Array<DocumentSingle> = [];
}

class DocumentSingle extends BaseDocument {
    methodBase() { };
    methodSingle() { console.log("MethodSingle by " + this.docName) };
}

I've given documents a docName so we can see some useful output later. Note how the children property of DocumentCollection is either an Array<DocumentCollection> or an Array<DocumentSingle>. This will prevent it from being a mixed collection which, if I understand correctly from your question, you want to prohibit. Note that it's harder to use a union-of-arrays than it is to use an array-of-unions, but it is what it is.

Let's give a name to the union of DocumentSingle and DocumentCollection:

type Document = DocumentSingle | DocumentCollection;

You will probably want to use Document instead of AbstractDocument or BaseDocument, if you can help it.


Now let's look at Tree:

class Tree {

    nodes: Document[]
    constructor(public rootNode: Document) {
        this.nodes = [];
        const addNodes = (x: Document): void => {
            this.nodes.push(x)
            if ("children" in x) {
                x.children.forEach(addNodes)
            }
        }
        addNodes(this.rootNode);

    }
    walk(
      processSingle: (x: DocumentSingle) => void, 
      processCollection: (x: DocumentCollection) => void
    ) {
        const walk = (x: Document): void => {
            if ("methodSingle" in x) {
                processSingle(x);
            } else {
                processCollection(x);
                x.children.forEach(walk)
            }
        }
        walk(this.rootNode);
    }
}

A Tree has a rootNode of type Document. It also has a nodes array of type Document[]. When you construct a Tree with its rootNode, the constructor will also walk the tree to build up the nodes array, if it matters. There's also a walk() method which takes processor callbacks for DocumentSingle and DocumentCollection and walks through the tree calling the appropriate processor.

Note that in the implementation of both the addNodes() and walk() arrow functions, the compiler uses the presence of one of the specific properties of DocumentSingle or DocumentCollection to narrow a Document to one of the two members. That works because the in operator can be used as a type guard.


So let's make a Tree:

const leafOne = new DocumentSingle("leafOne");
const leafTwo = new DocumentSingle("leafTwo");
const leafThree = new DocumentSingle("leafThree");
const leafFour = new DocumentSingle("leafFour");

const branchOne = new DocumentCollection("branchOne");
branchOne.children = [leafOne, leafTwo];

const branchTwo = new DocumentCollection("branchTwo");
branchTwo.children = [leafThree, leafFour];

const root = new DocumentCollection("root");
// note how I'm not allowed to assign a mixed thing to root.children
root.children = [branchOne, leafOne];

root.children = [branchOne, branchTwo]; // okay

const tree = new Tree(root);

You can see from the above that you are not allowed to use a mixed array of DocumentSingle and DocumentCollection in the children property of a DocumentCollection. Also you should note that I reassigned the children property with a fresh array instead of trying to push() onto it. If you try a push() you'll find that it won't let you add anything, because it doesn't know if the array holds DocumentSingles or DocumentCollections. Not sure if this is a dealbreaker or not for your use case, but if so we can change it. (Well, you can change it; I don't know that I can commit to it ⏳)

Great, we have a tree... let's walk() it:

tree.walk(x => x.methodSingle(), y => y.methodCollection());
/* [LOG]: "MethodCollection by root" 
[LOG]: "MethodCollection by branchOne" 
[LOG]: "MethodSingle by leafOne" 
[LOG]: "MethodSingle by leafTwo" 
[LOG]: "MethodCollection by branchTwo" 
[LOG]: "MethodSingle by leafThree" 
[LOG]: "MethodSingle by leafFour" */

Great! Alternatively, we could iterate its nodes property:

tree.nodes.forEach(x => "methodSingle" in x ? x.methodSingle() : x.methodCollection());
/* [LOG]: "MethodCollection by root" 
[LOG]: "MethodCollection by branchOne" 
[LOG]: "MethodSingle by leafOne" 
[LOG]: "MethodSingle by leafTwo" 
[LOG]: "MethodCollection by branchTwo" 
[LOG]: "MethodSingle by leafThree" 
[LOG]: "MethodSingle by leafFour" */

Looks good.


Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.