Michel Conrado Diz
Michel Conrado Diz

Reputation: 321

Reactjs and Typescript - Property 'select' does not exist on type 'EventTarget'

This type checking problem took me all day and I still have not solved it. I searched everywhere, but I see that no one has gone through it. Could someone give me a light? thank you!

 <input
        type="text"
        value={shareURLValue}
        className={classnames("share-url-holder", {
            shared: Boolean(shareId) && !shareHidden,
        })}
        ref={saveShareURLRef}
        onClick={e => {
            e.target.select(); #Property 'select' does not exist on type 'EventTarget'.
        }}
        onKeyUp={e => {
            e.target.select(); #Property 'select' does not exist on type 'EventTarget'.
        }}
    />

Upvotes: 1

Views: 3995

Answers (3)

Daniel Loiterton
Daniel Loiterton

Reputation: 5308

Here's how I got this working:

const handleSomeEvent = (e: SyntheticEvent<HTMLInputElement>) => {
  /* now you have type-safe access to all the things */
  e.currentTarget.[stuff]
}

return <input onClick={handleSomeEvent} onKeyUp={handleSomeEvent} {...otherProps}/>

Upvotes: 1

kingdaro
kingdaro

Reputation: 12028

Use e.currentTarget instead of e.target.

From the react type definitions:

interface SyntheticEvent<T> {
    // other properties...

    /**
     * A reference to the element on which the event listener is registered.
     */
    currentTarget: EventTarget & T;

    // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
    /**
     * A reference to the element from which the event was originally dispatched.
     * This might be a child element to the element on which the event listener is registered.
     *
     * @see currentTarget
     */
    target: EventTarget;
}

In other words, target might not be the input element when it's a MouseEvent. Use currentTarget to get the element that the event handler is bound to.

Upvotes: 7

klugjo
klugjo

Reputation: 20885

You need to be more explicit about the type of your event args:

onClick={(e: React.MouseEvent<HtmlInputElement>)  => {
            e.target.select(); #Property 'select' does not exist on type 'EventTarget'.
        }}

and

onKeyUp={(e: React.KeyBoardEvent<HtmlInputElement>) => {
            e.target.select(); #Property 'select' does not exist on type 'EventTarget'.
        }}

Upvotes: -1

Related Questions