1

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'.
        }}
    />

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems you right, I'll solve other issues (that showed up), do tests and come back to to you it worked out, I was afraid to do this (I had seen other examples as yours) because using "select" seems to me necessary. We'll see. I appreciate your help!
1

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}/>

Comments

-1

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

1 Comment

I appreciate your help! But your tip give me different checks in order: [ts] Cannot find name 'HtmlInputElement'. [ts] Namespace 'React' has no exported member 'KeyBoardEvent'.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.