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

avatar

Borislav Hadzhiev

Last updated: Mar 27, 2022

banner

Photo from Unsplash

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

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

property files 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> <label for="avatar">Choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg, image/webp" /> <button id="btn">Log files</button> <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('avatar'); input?.addEventListener('change', event => { // ⛔️ Property 'files' does not exist on type 'EventTarget'.ts(2339) console.log(event.target?.files); });

The reason we got the error is that the EventTarget interface does not contain a files property.

To solve the error, use a type assertion to type the element as HTMLInputElement.

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

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

You could also use the type assertion inline.

src/index.ts
const input = document.getElementById('avatar'); input?.addEventListener('change', event => { // 👇️ inline type assertion const result = (event.target as HTMLInputElement).files; 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.

The types are consistently named 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.

Conclusion #

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

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.