Object is possibly 'undefined'.ts(2532)
Senichi
Posted on July 8, 2022
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:
- Null References: The Billion Dollar Mistake
- How can I solve the error 'TS2532: Object is possibly 'undefined'?
- False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks
- 'Property does not exist on type 'never'
- TypeScript does not expect variable change in forEach
- TS2531: Object is possibly 'null'
- How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?
- Getting Object is possibly 'undefined' in typescript react
- 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;
Posted on July 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.