Reputation: 8925
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>
}
Upvotes: 17
Views: 25180
Reputation: 1075239
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.)
Upvotes: 54