13

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>
}
nima
  • 7,796
  • 12
  • 36
  • 53

1 Answers1

46

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 for you if you use null as the initializer, so you don't have to use <HTMLDivElement | null>, though it's fine if you do and you get the same result.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks for your explanation but my problem is persisting. I'm not using or any type for defining useRef (see my code snippet on question) – nima Jul 30 '21 at 11:37
  • 1
    I've recreated your code and it's working. @novonimo – Sajeeb Ahamed Jul 30 '21 at 11:41
  • @novonimo - You are using a `div`, here: `
    `. When I copy your code into a Preact/TypeScript project (`FunctionalComponent` tells me you're using Preact), I get the error you describe. When I add the type as shown in the answer above, the error goes away. Same thing if I do that in a React/TypeScript project and change `FunctionalComponent` to `FunctionComponent`. Perhaps you just didn't add the change correctly?
    – T.J. Crowder Jul 30 '21 at 11:43
  • I just edit my post and fix the FunctionCompnent. I'm using React and using FunctionComponent type @T.J.Crowder – nima Jul 30 '21 at 11:48
  • 1
    @novonimo - No, those errors do not occur with the code in the question amended as shown in the answer. Proof: https://codesandbox.io/s/recursing-pare-neihr?file=/src/App.tsx – T.J. Crowder Jul 30 '21 at 12:00