Wanna see something cool? Check out Angular Spotify 🎧

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

Read more

 — TypeScript data structure: Stack
 — TypeScript data structure: Queue
 — TypeScript data structure: Singly linked list
 — Difference between: function Person(){}, var person = Person(), and var person = new Person()?
 — Warning: Can’t perform a React state update on an unmounted component

Follow @trungvose on Twitter for more!