0

I am trying to use useRef as shown below with typescript strict set to On, but I keep getting 'Object is possibly 'undefined'.

  const inputRef = React.useRef();
  const updateSelectionStart = () =>
    setSelectionStart(inputRef.current.selectionStart);

I also tried with this:

const inputRef = useRef<HTMLInputElement>(null);
and
const inputRef = useRef<HTMLInputElement | null>(null);

And nothing.

Any suggestions about how to do it without typescript errors?

2 Answers2

0

Try using typescript optional chaining feature as below:

const inputRef = React.useRef();
  const updateSelectionStart = () =>
    setSelectionStart(inputRef.current?.selectionStart);
Ali Torki
  • 1,929
  • 16
  • 26
0

I fixed it by doing this:

const updateSelectionStart = () => {
    setCursorPosition(inputRef.current!.selectionStart || 0);
};