Property 'click' does not exist on type 'never'. TS2339

Viewed 9613

According to other similar issues about this type of error with TypeScript (on questions #44147937 and #40796374) I've found that assigning null to create a state or reference will cause this problem: Property ... does not exist on type 'never'

how to handle this issue in this example component?

const FooComponent: FunctionComponent<FooInterface> = () => {

    const myRef = useRef(null)

    const handleClickOnButton = () => myRef?.current?.click();

    return (
       <div>
           <div ref={myRef} />
           <button onClick={handleClickOnButton} />
       </div>
}
1 Answers

TypeScript can't infer the type of the ref from where you use it later in the code, you have to tell it the type of the ref:

const ref = useRef<HTMLDivElement>(null);
// −−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^

(useRef adds the null type to the type parameter you give it, soyou don't have to use <HTMLDivElement | null>.)

Related