typescript 如何避免打字稿错误:“元素”类型上不存在属性“innerHTML”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35252872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:53:35  来源:igfitidea点击:

How to avoid typescript error: Property 'innerHTML' does not exist on type 'Element'

typescript

提问by Ivan

I'm trying to place some HTML inside a specific div. When I try this in typescript I get this error: Property 'innerHTML' does not exist on type 'Element'. Basicly, this is the code:

我正在尝试将一些 HTML 放在特定的 div 中。当我在打字稿试试这个我得到这个错误: Property 'innerHTML' does not exist on type 'Element'。基本上,这是代码:

document.body.innerHTML = '<div id="myDiv"><div>'

let myContainer = document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';

Amazingly, it still works when typescripts compiles, but I'm wondering if typescript is giving me an error, what's the right way to go on assigning innerHTML in this case?

令人惊讶的是,它在 typescripts 编译时仍然有效,但我想知道 typescript 是否给我一个错误,在这种情况下继续分配 innerHTML 的正确方法是什么?

回答by Vadim Macagon

Use a type assertion to placate the compiler:

使用类型断言来安抚编译器:

let myContainer = <HTMLElement> document.querySelector("#myDiv");
myContainer.innerHTML = '<h1>Test</h1>';

回答by Martin Vseticka

In future versions of TypeScript, it should not be necessary to do the casting. I've sent a pull request to fix the issue:

在 TypeScript 的未来版本中,不需要进行转换。我已经发送了一个拉取请求来解决这个问题:

回答by Ariel Massillo

I had the same issue, solved it by declaring it as:

我遇到了同样的问题,通过将其声明为:

myString = 'hello world';

var el: HTMLElement = document.getElementById('id_of_element');
el.innerHTML = myString;

回答by Karol Majewski

The only type-safe way to modify DOM elements is to verify they exist first. TypeScript is smart enough to tell you that document.querySelectorcan return nullwhen the target is not found in the document.

修改 DOM 元素的唯一类型安全方法是首先验证它们是否存在。TypeScript 足够聪明,可以告诉您在文档中找不到目标时document.querySelector可以返回null

document.body.innerHTML = '<div id="myDiv"><div>'

let myContainer: HTMLDivElement | null = document.querySelector("#myDiv");

if (myContainer instanceof HTMLDivElement) {
    myContainer.innerHTML = '<h1>Test</h1>';
}

The above code compiles without error in TypeScript 3.2.1.

上面的代码在 TypeScript 3.2.1 中编译没有错误。

回答by Mukesh

Use like this (<HTMLElement>document.querySelector("#myDiv")).innerHTML

Use like this (<HTMLElement>document.querySelector("#myDiv")).innerHTML