Adding existing functions in TypeScript: Node.getAttribute()

跟風遠走 提交于 2021-02-11 15:20:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!