问题
What is the best way to add a function to typescript that actually exists already? In my case this is Node.getAttribute()
, which is actually built-in to the browser, but not yet recognized by TypeScript. It errors: Cannot find property 'getAttribute' on type 'Node'.
In my case I ran into this error executing the following:
var xmlDocument = new DOMParser().parseFromString(xmlString, "text/xml"),
rootfile = xmlDocument.getElementsByTagName("aNode")[0];
console.log(rootfile.getAttribute("anAttribute"));
This succeeds in the browser, but throws an error by TypeScript.
回答1:
Since interfaces are open ended just tell typescript about it:
interface Node {
getAttribute(attr: string): string;
}
I recommend doing this in a globals.d.ts
file at the root of your project.
回答2:
You should look for the d.ts files for Node at definitely typed https://github.com/borisyankov/DefinitelyTyped That would be easier than rewriting the whole node definitions by hand...
来源:https://stackoverflow.com/questions/30429520/adding-existing-functions-in-typescript-node-getattribute