2
0

More than 1 year has passed since last update.

event.target と型の話

Last updated at Posted at 2022-10-27

知っている人からすれば「だから何」という話ですが、ちょっと面白かったので小ネタを。

この記事のサンプルコードは React TSX で書いていますが、今回の話題では React は関係ないです

React + TypeScript を書いていたとき、下記のコードで型エラーが出ました。

// Property 'src' does not exist on type 'EventTarget'.ts(2339)
<img src="foo.png" onClick={(event) => console.log(event.target.src)} />

これを、こう書き換えたら型エラーは消えました。

// エラーなし
<img src="foo.png" onClick={(event) => console.log(event.currentTarget.src)} />

一瞬「どちらも event.target には HTMLImageElement が入るはずなのに何故変わる?」と思ったのですが、少し考えれば「それはそう」となりました。

この振る舞いの違い、説明できるでしょうか?

この記事は書きかけなので解説はあとで書きます (もしくは誰かがコメントしてくれる)
→ コメントに書きました

2
0
4

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
2
0