70
55

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型ではまった

Last updated at Posted at 2015-11-16

Typescriptでイベント発生元の情報を取りたい時に、Javascriptのノリで書いていたら怒られた
具体的には下記
inputのvalueをとろうとしたら、んなもんねぇよ!と怒られた

あれ・・・valueがいない・・・
var element = document.createElement('input');
element.value = 'test';
element.addEventListener('click', function(event: MouseEvent) {
	alert(event.target.value); // Property 'value' does not exist on type 'EventTarget'.
}, false);
element.click();

EventTargetにはHTMLElementが必ずしも来るわけでないらしい
https://developer.mozilla.org/ja/docs/Web/API/EventTarget

Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.

targetにHTMLElementが来る用のinterfaceを用意して解決した

欲しいHTMLElementを指定したinterface
interface HTMLElementEvent<T extends HTMLElement> extends Event {
	target: T;
}

var element = document.createElement('input');
element.value = 'test';
element.addEventListener('click', function(event: HTMLElementEvent<HTMLInputElement>) {
	alert(event.target.value); // 補完できるヤッター
}, false);
element.click();

Demo

70
55
0

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
70
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?