{"id":192,"hash":"9539a606342e02755e09de5f04633439fc96662bf1c68dc16bb1fe6a04dc14b8","pattern":"How to suppress &quot;error TS2533: Object is possibly &#39;null&#39; or &#39;undefined&#39;&quot;?","full_message":"I have a type:\n\ntype tSelectProtected = {\n  handleSelector?: string,\n  data?: tSelectDataItem[],\n\n  wrapperEle?: HTMLElement,\n  inputEle?: HTMLElement,\n  listEle?: HTMLElement,\n  resultEle?: HTMLElement,\n\n  maxVisibleListItems?: number\n}\n\nI declare a global module-wise variable:\n\nvar $protected : tSelectProtected = {};\n\nI'm assigning proper value in function1() scope:\n\n$protected.listEle = document.createElement('DIV');\n\nLater in function2() scope, I'm calling:\n\n$protected.listEle.classList.add('visible');\n\nI'm getting TypeScript error:\n\nerror TS2533: Object is possibly 'null' or 'undefined'\n\nI 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.\n\nHow this situation can or should be handled without disabling TS compiler checks?","ecosystem":"npm","package_name":"typescript","package_version":null,"solution":"This feature is called \"strict null checks\", to turn it off ensure that the --strictNullChecks compiler flag is not set.\n\nHowever, the existence of null has been described as The Billion Dollar Mistake, so it is exciting to see languages such as TypeScript introducing a fix. I'd strongly recommend keeping it turned on.\n\nOne way to fix this is to ensure that the values are never null or undefined, for example by initialising them up front:\n\ninterface SelectProtected {\n    readonly wrapperElement: HTMLDivElement;\n    readonly inputElement: HTMLInputElement;\n}\n\nconst selectProtected: SelectProtected = {\n    wrapperElement: document.createElement(\"div\"),\n    inputElement: document.createElement(\"input\")\n};\n\nSee Ryan Cavanaugh's answer for an alternative option, though!","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/40349987/how-to-suppress-error-ts2533-object-is-possibly-null-or-undefined","votes":573,"created_at":"2026-04-19T04:41:29.538455+00:00","updated_at":"2026-04-19T04:51:11.499634+00:00"}