13

I am trying to construct an event listener callback that detects where it has been invoked from, similar to this:

import { TouchEvent } from 'react'

const isInvokedFromInsideContainer = (event: TouchEvent<HTMLElement>) => {
  parentContainer = event.target.closest('#container')
  console.log('isInvokedFromInsideContainer: ' + !!parentContainer)
}

but I get

TS2339: Property 'closest' does not exist on type 'EventTarget'

event.nativeEvent.target.closest doesn't work either
event.currentTarget.closest works, but I obviously don't want that

Casting target as HTMLElement works:

const target = (event.target as HTMLElement)
const parentContainer = target.closest('#container')

What is the correct way to do this?

3
  • 2
    Did you ever resolve this? I have the same issue?
    – U4EA
    Jul 5, 2020 at 16:08
  • 2
    Unfortunately not, ended up casting the type as mentioned above. Let me know if you figure it out :) Jul 5, 2020 at 19:09
  • I just ended up type casting, too.
    – U4EA
    Jul 7, 2020 at 15:55

2 Answers 2

10

I fixed this error by directly casting event.target as HTMLElement

So in your case:

...
  parentContainer = (event.target as HTMLElement).closest('#container')
...
6

You can make Typescript understand which type the target is by asserting its constructor:

if (event.target instanceof HTMLElement) {
  const container = event.target.closest('#container')
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.