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)
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 settingmyRef.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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With