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"
/>
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.
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"
/>