Typescript: How to check if variable is of type Element? ReferenceError: Element is not defined

155 views Asked by At

I am using Node with TypeScript and the xmldom package to parse an xml file and iterate over it to convert it into JavaScript classes. For this, I am iterating over childNodes with

constructor(xmlElement: Element) {
    for (let childNode of xmlElement.childNodes) {
        if (childNode instanceof Element) {
            if(childNode.tagName=="myTag") { /* do something depending on which tag it is*/ }
            /* a lot of similar if statements */
        }
        else {
            /* do something for text nodes*/
        }
    }
}

However running this code gives me the error message: "ReferenceError: Element is not defined". Even though it should exist as a standard class of JavaScript, if I am not mistaken.

Using if(childNode.nodeType == Node.ELEMENT_NODE) as suggested in 9979172 throws the error Node is not defined. Using if(childNode.innerHTML) works logic wise and the code runs as intended, but TypeScript is not able to infer that this is equivalent to childNode instanceof Element and marks every if statement using childNode.tagName of childNode.innerHTML down the line as a TypeScript error and adding //@ts-ignore to every second line defeats the purpose of using TypeScript.

I read in a related question that Element probably doesn't exists in Node, because there is no DOM on the server, if that's the case I'm looking for an alternative solution, which doesn't cause TypeScript errors.

0

There are 0 answers