The following code works fine but trying to address the error alert coming from Typescript
.
It keeps warning me with following error for the usage of ref.currrent.value
.
ERROR 1. TS18048: 'ref.current' is possibly 'undefined'.
Fair enough. So I add in a check as follows.
const result = ref.current && ref.current.value;
This now throws following error.
ERROR 2. TS2339: Property 'value' does not exist on type 'never'.
Error also shown when I use the useRef
for an input as show in code below.
I have tried to force these types on the useRef<Type>
but results in same error.
ERROR 3: TS2322: Type 'MutableRefObject' is not assignable to type 'LegacyRef | undefined'. Type 'MutableRefObject' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'undefined' is not assignable to type 'HTMLInputElement | null'.
How can I address these errors. No issues faced in the logic but the red squiggly lines defeats the purpose of using Typescript. Pls advice. Thanks.
P.S: This is a nextjs project if that matters.
State management in use here is Zustand but leaving that tag out cos believe it is irrelevant here.
Issue is with useRef
hook validation I believe.
Code:
'use client';
import {useRef} from "react";
import useStore from "../utils/store";
const Input = () => {
const addPerson = useStore((state) => state.addPerson);
const ref = useRef();
const add = () => {
const result = ref.current && ref.current.value; // ERROR 2
ref.current.value = ''; // ERROR 1
addPerson({
name: result,
id: '2',
});
}
return (
<div>
<input placeholder='write something' type='text' ref={ref} /> {/* ERROR 3*/}
<button onClick={add}>Add Person</button>
</div>
);
};
export default Input;
Image to show the red error lines:
CodePudding user response:
This may work
'use client';
import {useRef} from "react";
import useStore from "../utils/store";
const Input = () => {
const addPerson = useStore((state) => state.addPerson);
const ref = React.useRef<HTMLInputElement>(null);
const add = () => {
const result = ref.current && ref.current.value; // ERROR 2
if (ref.current) {
ref.current.value = ''; // ERROR 1
}
addPerson({
name: result,
id: '2',
});
}
return (
<div>
<input placeholder='write something' type='text' ref={ref} /> {/* ERROR 3*/}
<button onClick={add}>Add Person</button>
</div>
);
};
export default Input;
Here is the original answer, I just put an extra falsy check
Hope it helps