0

将函数添加到实际已经存在的打字稿的最佳方法是什么?在我的例子中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 引发错误。

4

2 回答 2

1

由于接口是开放式的,只需告诉 typescript 即可:

interface Node {
    getAttribute(attr: string): string;
}

我建议在globals.d.ts项目根目录的文件中执行此操作。

于 2015-05-24T23:49:04.080 回答
0

您应该在明确键入的https://github.com/borisyankov/DefinitelyTyped中查找 Node 的 d.ts 文件, 这比手动重写整个节点定义要容易...

于 2015-05-25T10:14:47.227 回答