#Property does not exist on type 'EventTarget'.

23 messages · Page 1 of 1 (latest)

slim chasm
#

I am creating a function that takes mouse and keyboard events.

function addToGuessedLetters(e: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>) {
    const button = e.target;
    setGuessedLetters((prevLetters) => [...prevLetters, button.textContent]);
    if (wordToGuess.includes(button.textContent.toLowerCase())) {
        button.setAttribute("data-true", "");
    } else {
        button.setAttribute("data-false", "");
    }
}

But I get this error: "Property 'textContent' does not exist on type 'EventTarget'.". Same error in "setAttribute" as well. What should I do?

I tried "e.target?.textContent" and "const button = e.target as HTMLElement" but didn't work.

scarlet gale
#

try currentTarget instead of target

#

in const button = e.target;

slim chasm
#

Now it gives a "it could be null" error

#

Should I try type narrowing in this code snippet?

scarlet gale
#

right, in theory, the currentTarget could be null

#

but in reality, your callback got called, so the element did recieve the event

#

is it's not null

#

you can safely ignore the null possibility in this case

#

you can use the non-null assertion operator (!) to tell TS the property won't ever be null

#

const button = e.currentTarget!;

#

or you can always do the check first, check if the currentTarget is not null, then proceed

slim chasm
#

It worked, thank you

#

Do we always use event.currentTarget in TypeScript?

scarlet gale
#

it's not about TypeScript

#

it's mostly a React thing

#

you'd be writing about the exact same code in JS

#

(except for the ! assertion ofc)

slim chasm
#

Hmm I got it

#

Thanks again

scarlet gale
#

The values of currentTarget, eventPhase, target, and type reflect the values your React code expects. Under the hood, React attaches event handlers at the root, but this is not reflected in React event objects. For example, e.currentTarget may not be the same as the underlying e.nativeEvent.currentTarget. For polyfilled events, e.type (React event type) may differ from e.nativeEvent.type (underlying type).
React magic at its finest

#

tldr.
when using raw JS (without React, target and currenttarget should be the same)
when using React, it might not be, because of how React works