在TypeScript中添加现有函数:Node.getAttribute()

时间:2015-05-24 23:45:17

标签: typescript typescript1.5

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

2 个答案:

答案 0 :(得分:1)

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

<li><a href="content1.php" data-target="#right_section">Some Content</a></li>

$('[data-target]').click( function (e) {
var target = $($(this).attr('data-target'));
target.load($(this).attr('href'));
e.preventDefault(); // prevent anchor from changing window.location
});

<div id="right_section"></div>

我建议在项目根目录的interface Node { getAttribute(attr: string): string; } 文件中执行此操作。

答案 1 :(得分:0)

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