18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptのaddEventListenerで「EventTargetの中にそんなプロパティないよ」と怒られる問題について

Posted at

どんな問題?

JSっぽくこんな風に書くと「EventTargetの中にそんなプロパティないよ」とTypeScript先生に怒られてしまいます。

const element = document.querySelector("#piyopiyo");
element!.addEventListener("click", (e) => {
    let target = e.target;
    console.log(target.innerText);
})

// エラー!
// Property 'innerText' does not exist on type 'EventTarget'.

解決方法

as HTMLElementでキャストすることで解決できます。これが一番簡単だと思います。

const element = document.querySelector("#piyopiyo");
element!.addEventListener("click", (e) => {
    let target = e.target as HTMLElement;    // <-- ココ!
    console.log(target.innerText);
})

参考
javascript - error " Property 'innerText' does not exist on type 'EventTarget' "? - Stack Overflow

他の解決方法のご紹介(interfaceの利用)
TypescriptでaddEventListener時のEventTarget型ではまった - Qiita

原因

EventTargetはHTMLElementじゃないからダメ」というお話みたいです。
JavaScriptの場合はEventTargetでもHTMLElementのプロパティをそのまま使えましたが、TypeScriptの場合は一度明示的にキャストする必要があるみたいです。

TypescriptでaddEventListener時のEventTarget型ではまった - Qiita
EventTarget - Web API | MDN

参考リンク

18
9
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?