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

后端 未结 6 2002
时光说笑
时光说笑 2020-12-16 09:14

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\'

6条回答
  •  我在风中等你
    2020-12-16 09:57

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

    document.body.innerHTML = '
    ' let myContainer: HTMLDivElement | null = document.querySelector("#myDiv"); if (myContainer instanceof HTMLDivElement) { myContainer.innerHTML = '

    Test

    '; }

    The above code compiles without error in TypeScript 3.2.1.

提交回复
热议问题