DEV Community

Cover image for Object is possibly 'undefined'.ts(2532)
Senichi
Senichi

Posted on

Object is possibly 'undefined'.ts(2532)

Let me tell you now, there is no solution, but there is a method of deal with the error.

Microsoft team member for Typescript said in a related trend that "This is working as intended".

Many developers are talking about this from different use cases as arrays, function callbacks, string values, html elements inside a React components (my case), and the list grows and grows...

I could found suggested solution that it doesn't worked, as background is that "The type system would effectively have to make a distinction between empty and non-empty arrays which isn't something we track".

So, a few links where this is discussed:

  1. Null References: The Billion Dollar Mistake
  2. How can I solve the error 'TS2532: Object is possibly 'undefined'?
  3. False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks
  4. 'Property does not exist on type 'never'
  5. TypeScript does not expect variable change in forEach
  6. TS2531: Object is possibly 'null'
  7. How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?
  8. Getting Object is possibly 'undefined' in typescript react
  9. Annotate immediately-invoked functions for inlining flow control analysis

Suppressing errors

  • the deal

Suppress errors in .ts files using ’// @ts-ignore’ comments

A // @ts-ignore comment suppresses all errors that originate on the following line. It is recommended practice to have the remainder of the comment following @ts-ignore explain which error is being suppressed.

Please note that this comment only suppresses the error reporting, and we recommend you use this comments very sparingly.

How I solve this

  • "the right combination of types and assertion"

So, TypeScript also has a special syntax for removing null and undefined from a type without doing any explicit checking. Writing ! after any expression is effectively a type assertion that the value isn’t null or undefined:

# case
const textElementRef = useRef();
// this provokes the error in the next line
const text = textElementRef.current;
// Object is possibly 'undefined'.ts(2532)'
const textWidth = text.offsetWidth;

# what I was trying
const textElementRef = useRef();
const text = textElementRef.current; 
const textWidth = text!.offsetWidth; <-- type assertion
// causing : Property 'offsetWidth' does not exist on type 'never'.ts(2339)

# then I have to change the useRef definition too
const textElementRef = useRef<HTMLSpanElement>(null);
const text = textElementRef.current!; <-- type assertion
const textWidth = text.offsetWidth;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)