Property 'value' does not exist on type 'EventTarget' in TS

avatar

Borislav Hadzhiev

Sun Mar 27 20222 min read

Property 'value' does not exist on type 'EventTarget' in TS #

The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget. To solve the error, use a type assertion to type the element correctly before accessing the property.

property value not exist type eventtarget

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="first_name" type="text" name="first_name" value="Initial Value" /> <script src="./src/index.ts"></script> </body> </html>

And here is an example of how the error occurs in the index.ts file.

src/index.ts
const input = document.getElementById('first_name'); input?.addEventListener('input', event => { // ⛔️ Property 'value' does not exist on type 'EventTarget'.ts(2339) console.log(event.target?.value); });

The reason we got the error is because the EventTarget interface does not contain a value property.

To solve the error, use a type assertion to type the element as HTMLInputElement (or HTMLTextAreaElement if you're working with a textarea element).

src/index.ts
const input = document.getElementById('first_name'); input?.addEventListener('input', event => { const target = event.target as HTMLInputElement; console.log(target.value); });

We assigned the event.target property to a target variable and typed it as an HTMLInputElement so we can access its value property.

You could also use the type assertion inline.

src/index.ts
const input = document.getElementById('first_name'); input?.addEventListener('input', event => { // 👇️ inline type assertion const result = (event.target as HTMLInputElement).value; console.log(result) });

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the target variable stores anHTMLInputElement and not to worry about it.

If you have a textarea element, you would use the HTMLTextAreaElement type.

src/index.ts
const textarea = document.getElementById('message'); textarea?.addEventListener('input', event => { const target = event.target as HTMLTextAreaElement; console.log(target.value); });

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, etc.

Use the search field on my Home Page to filter through my more than 1,000 articles.