在 TypeScript 中添加现有函数:Node.getAttribute()
Adding existing functions in TypeScript: Node.getAttribute()
向实际已经存在的打字稿添加函数的最佳方法是什么?在我的例子中,这是 Node.getAttribute()
,它实际上内置于浏览器中,但尚未被 TypeScript 识别。它错误:Cannot find property 'getAttribute' on type 'Node'.
在我的例子中,我 运行 执行以下错误:
var xmlDocument = new DOMParser().parseFromString(xmlString, "text/xml"),
rootfile = xmlDocument.getElementsByTagName("aNode")[0];
console.log(rootfile.getAttribute("anAttribute"));
这在浏览器中成功,但 TypeScript 抛出错误。
由于接口是开放式的,只需告诉 typescript 即可:
interface Node {
getAttribute(attr: string): string;
}
我建议在项目根目录下的 globals.d.ts
文件中执行此操作。
您应该在绝对类型 https://github.com/borisyankov/DefinitelyTyped 处寻找 d.ts Node 文件
这比手动重写整个节点定义要容易...
我相信如果您将代码更改为以下代码,它应该一切正常。
rootfile = xmlDocument.getElementsByTagName("aNode")[0] as HTMLElement;
向实际已经存在的打字稿添加函数的最佳方法是什么?在我的例子中,这是 Node.getAttribute()
,它实际上内置于浏览器中,但尚未被 TypeScript 识别。它错误:Cannot find property 'getAttribute' on type 'Node'.
在我的例子中,我 运行 执行以下错误:
var xmlDocument = new DOMParser().parseFromString(xmlString, "text/xml"),
rootfile = xmlDocument.getElementsByTagName("aNode")[0];
console.log(rootfile.getAttribute("anAttribute"));
这在浏览器中成功,但 TypeScript 抛出错误。
由于接口是开放式的,只需告诉 typescript 即可:
interface Node {
getAttribute(attr: string): string;
}
我建议在项目根目录下的 globals.d.ts
文件中执行此操作。
您应该在绝对类型 https://github.com/borisyankov/DefinitelyTyped 处寻找 d.ts Node 文件 这比手动重写整个节点定义要容易...
我相信如果您将代码更改为以下代码,它应该一切正常。
rootfile = xmlDocument.getElementsByTagName("aNode")[0] as HTMLElement;