Michal Kurz
Michal Kurz

Reputation: 2095

TS2339: Property 'closest' does not exist on type 'EventTarget'. - How do I get native event.target in React?

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?

Upvotes: 24

Views: 11146

Answers (2)

Kenneth Sundqvist
Kenneth Sundqvist

Reputation: 483

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')
}

Upvotes: 16

Zac
Zac

Reputation: 2081

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

So in your case:

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

Upvotes: 21

Related Questions