Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Object is possibly 'null' focusing using ref in react

typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

myRef && myRef.current && myRef.current.focus();

if I use

myRef?.current?.focus();

I got

Property 'focus' does not exist on type 'never'.ts(2339)
like image 541
Andre Thonas Avatar asked Jan 26 '23 00:01

Andre Thonas


2 Answers

When you define your reference, you should specify what type it will be:

const myRef = useRef<HTMLElement>(null);

(Note that the above assumes you're using it like <div ref={myRef}> - if you're setting myRef.current manually, you need to specify the type as <HTMLElement|null>.

Once you have done this, you should be able to use the following:

myRef.current?.focus()

Note that you do not need to use the existential check on myRef - that will always be an object with a current property - that's how react's API works.

like image 172
Ed_ Avatar answered Jan 27 '23 14:01

Ed_


To make typescript silent and tell typescript you know what you are doing. you can use exclamation mark(!) before the variable you know that it can be null. Like in existing scenario if "current" can be null in some scenarios and you want that typescript do not show error on it.

myRef.!current.focus()
like image 26
MuhammadUsman Avatar answered Jan 27 '23 13:01

MuhammadUsman