It is important to put the correct type of event, but I tend to put it on in a messy way because I donât know what the correct type is (my mistake in the past). You donât have to remember the correct event type or anything, just âmake it void or some other type that is obviously incorrect, and TypeScript will tell you the correct answer and you can use itâ.
context
qnighy e.target often used incorrectly issue
nishio This reminds me of recently when I passed e directly to foo and then looked at the completion candidates and thought âhmmm, currentTarget, I donât know this kid, but it has the expected type, so Iâll take it, Iâll look it up later. ts
the âlike thisâ trend
type information
event.target: EventTarget
event.currentTarget: EventTarget & HTMLDivElement
MDN
- Event.currentTarget
-
Events traverse the DOM and identify the current target of the event. It always refers to the element to which the event handler is attached, as opposed to event.target, which identifies the element on which the event occurred.
-
- Event.target
-
A reference to the object that fired the event. Unlike event.currentTarget when the event handler is called during the bubbling or capture phase.
-
Ah, I see, so target can be any of the child elements, but currentTarget is the DOM element with the event handler. So the event: React.DragEvent<HTMLDivElement>
type argument that says âThis is an HTMLDivElement
â does not affect target, but currentTarget does.
This means that I was unknowingly protected from pitfalls by correctly typing events, but I donât think I typed events correctly when I first prototyped with TypeScript+React, just to see what would happen. If it is implicit any, I get a warning and have to explicitly set it to any, or say event: Event.
The âimplicit anyâ means that the type information cannot be guessed, so a human must type it properly, and it cannot be detected if you type it incorrectly. As a result, the implementation of the contents of the event handler may not get the support of the type. ts
Knowing the correct event types in React+TypeScript (this page) Since I noticed this technique, it has become easier for me to put the correct type on, but where do I learn these things?
This page is auto-translated from /nishio/React+TypeScriptă§æŁăăă€ăăłăăźćăç„ă using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. Iâm very happy to spread my thought to non-Japanese readers.