lhk
lhk

Reputation: 30146

typescript incorrect null/never checks with react refs

I'm setting up a react ref which I would like to use in useEffect. The compiler complains that myRef.current evaluates to never:

import React, {useRef, useState} from 'react'

export default function RefProblem() {
    const myRef = useRef(null);
    useState(()=>{
        console.log(myRef.current);

        // this line causes a compiler error
        myRef.current?.addEventListener('test', ()=>{})
    })
    return (
        <p ref={myRef}>text</p>
    );
}

The error message is:

error TS2339: Property 'addEventListener' does not exist on type 'never'.

It would be a valid concern that the current property might be null, that's why I'm using the null aware chaining operator ?. But it's definitely not never, if I run this, the console output will log a p element.

Am I overlooking something, or is this a bug in the typechecking?

Upvotes: 5

Views: 1333

Answers (1)

lhk
lhk

Reputation: 30146

The fix is to use the generic useRef and to specify the type of element that will be referenced:

const myRef = useRef<HTMLParagraphElement>(null);

Upvotes: 5

Related Questions