Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

Tags:

typescript

I have a type:

type tSelectProtected = {   handleSelector?: string,   data?: tSelectDataItem[],    wrapperEle?: HTMLElement,   inputEle?: HTMLElement,   listEle?: HTMLElement,   resultEle?: HTMLElement,    maxVisibleListItems?: number } 

I declare a global module-wise variable:

var $protected : tSelectProtected = {}; 

I'm assigning proper value in function1() scope:

$protected.listEle = document.createElement('DIV'); 

Later in function2() scope, I'm calling:

$protected.listEle.classList.add('visible'); 

I'm getting TypeScript error:

error TS2533: Object is possibly 'null' or 'undefined' 

I know that I can do explicit check using if ($protected.listEle) {$protected.listEle} to calm down compiler but this seems to be very unhandy for most non trivial cases.

How this situation can or should be handled without disabling TS compiler checks?

like image 936
grasnal Avatar asked Oct 31 '16 20:10

grasnal


People also ask

How do you suppress an object that is possibly null?

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.

How do I tell TypeScript to ignore undefined?

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.


1 Answers

If you know from external means that an expression is not null or undefined, you can use the non-null assertion operator ! to coerce away those types:

// Error, some.expr may be null or undefined let x = some.expr.thing; // OK let y = some.expr!.thing; 
like image 118
Ryan Cavanaugh Avatar answered Oct 16 '22 05:10

Ryan Cavanaugh