I've got the "Object is possibly null" error many times and usually I use a safety "if statement" in case it returns null.
I've got the following function:
const ModalOverlay = (props: any[]) => { const overlayEl = useRef(null); useEffect(() => { overlayEl.current.focus(); }); return <div {...props} ref={overlayEl} />; }
But overlayEl.current
gets the error "Object is not defined". So I've tried:
if (!overlayEl) { return null } else { useEffect(() => { overlayEl.current.focus(); }); return <div {...props} ref={overlayEl} />; }
Which didn't work. I've tried also:
overlay && overlayEl.current.focus();
Any hints would be highly appreciated! Thanks
The "Object is possibly 'null'" error occurs when we try to access a property on an object that may have a value of null . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not null before accessing properties.
Sometimes the TypeScript compiler isn't able to determine what type of value it may at a certain point. By adding the exclamation mark ( ! ) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null.
The error "Property does not exist on type 'never'" occurs when we forget to type a state array or don't type the return value of the useRef hook. To solve the error, use a generic to explicitly type the state array or the ref value in your React application.
When you declare const overlayEl = useRef(null); Makes the type it comes out as is null because that's the best possible inference it can offer with that much information, give typescript more information and it will work as intended.
Try....
const overlayEl = useRef<HTMLDivElement>(null);
Alternatively some syntax sugar for if you don't care for when its undefined is to do something like this.
const overlayEl = useRef(document.createElement("div"))
using the above syntax all common DOM methods just return defaults such as "0" i.e overlayEl.offsetWidth, getBoundingClientRect etc.
Usage:
if(overlayEl.current) { // will be type HTMLDivElement NOT HTMLDivElement | null const whattype = overlayEl.current; }
The way this works is typescripts static analysis is smart enough to figure out that if
check "guards" against null, and therefore it will remove that as a possible type from the union of null | HTMLDivElement
within those brackets.
const overlayEl = useRef() as MutableRefObject<HTMLDivElement>;
It will cast overlayEl
to an initiated MutableRefObject that is the returning value of useRef
:
function useRef<T = undefined>(): MutableRefObject<T | undefined>;
Yet in this case, the compiler will always think that overlayEl
has a value.
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