如何避免打字稿错误:“元素"类型上不存在属性“innerHTML" [英] How to avoid typescript error: Property 'innerHTML' does not exist on type 'Element'

查看:32
本文介绍了如何避免打字稿错误:“元素"类型上不存在属性“innerHTML"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在特定 div 中放置一些 HTML.当我在打字稿中尝试此操作时,出现此错误:Property 'innerHTML' 在类型 'Element' 上不存在.基本上,这是代码:

document.body.innerHTML = '

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

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

解决方案

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

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

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:

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?

解决方案

Use a type assertion to placate the compiler:

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

这篇关于如何避免打字稿错误:“元素"类型上不存在属性“innerHTML"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆