Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Paige Muller
Use a type assertion to type event.target
in TypeScript, e.g.
const target = event.target as HTMLInputElement
. Once typed correctly, you can
access any element-specific properties on the target
variable.
This is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <input id="message" type="text" name="message" value="Initial Value" /> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
// 👇️ const input: HTMLInputElement | null const input = document.getElementById('message') as HTMLInputElement | null; input?.addEventListener('input', function (event) { const target = event.target as HTMLInputElement; console.log(target.value); });
We used a
type assertion
to type event.target
as an HTMLInputElement
.
target
variable stores anHTMLInputElement
and not to worry about it.The types are consistently named as HTML***Element
. Once you start typing
HTML..
, your IDE should be able to help you with autocomplete.
Some commonly used types are: HTMLInputElement
, HTMLButtonElement
,
HTMLAnchorElement
, HTMLImageElement
, HTMLTextAreaElement
,
HTMLSelectElement
, etc.
If you aren't accessing any element-specific properties, you can also use the
more generic HTMLElement
type.
const input = document.getElementById('message') as HTMLInputElement | null; input?.addEventListener('input', function (event) { const target = event.target as HTMLElement; console.log(target.id); });
This is necessary, because the EventTarget
interface contains only a few
properties like addEventListener
, removeEventListener
and dispatchEvent
.
You can also use a type assertion inline.
const input = document.getElementById('message') as HTMLInputElement | null; input?.addEventListener('input', function (event) { // 👇️ type assertion inline const value = (event.target as HTMLInputElement).value; console.log(value); });
We effectively tell TypeScript that the event.target
property stores an
HTMLInputElement
and not to worry about it.
If you have a textarea element, you would use the HTMLTextAreaElement
type.
const input = document.getElementById('message') as HTMLTextAreaElement | null; input?.addEventListener('input', function (event) { const target = event.target as HTMLTextAreaElement; console.log(target.value); });
Other commonly used types are: HTMLInputElement
, HTMLButtonElement
,
HTMLAnchorElement
, HTMLImageElement
, HTMLDivElement
, HTMLSelectElement
,
etc.