How to type event.target in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 31, 2022

banner

Photo from Unsplash

Type event.target in TypeScript #

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.

index.html
<!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.

src/index.ts
// 👇️ 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.

We effectively tell TypeScript that the 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.

src/index.ts
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.

src/index.ts
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.

src/index.ts
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.