Wanna see something cool? Check out Angular Spotify 🎧
All Articles

TypeScript - Property 'onerror' does not exist on type 'EventTarget'

Problem

Recently, I converted one legacy React component to TS, and this error starts to appear.

Property 'onerror' does not exist on type 'EventTarget'

<img
  className="vip-badge-avatar"
  src={`https://www.gravatar.com/avatar/${md5(
    user.email.toLowerCase()
  )}?size=80&d=blank`}
  onError={(e) => {
    e.target.onerror = null;
    e.target.src = userDefaultPicture;
  }}
  alt="Profile Avatar"
/>

Property 'onerror' does not exist on type 'EventTarget

Reason

By default an event target element has an EventTarget type in TypeScript. It has just a few properties that we can use, and most of the time, we will need to assert the event type to the correct type.

Solution

If I assert the type of the event target to HTMLImageElement, the TS error went away. The HTMLImageElement interface represents an HTML <img> element, providing the properties and methods used to manipulate image elements.

<img
  className="vip-badge-avatar"
  src={`https://www.gravatar.com/avatar/${md5(
    user.email.toLowerCase()
  )}?size=80&d=blank`}
  onError={(e) => {
    (e.target as HTMLImageElement).onerror = null;
    (e.target as HTMLImageElement).src = userDefaultPicture;
  }}
  alt="Profile Avatar"
/>
Published 3 Jul 2021

Recent Posts

TypeScript data structure: Singly linked list

My implementation for singly linked list using TypeScript

TypeScript data structure: Stack

My implementation for Stack using TypeScript


Follow @tuantrungvo on Twitter for more!