debugtypescriptCritical
How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?
Viewed 0 times
errorobjecthowts2533possiblysuppressundefinednull
Problem
I have a
I declare a global module-wise variable:
I'm assigning proper value in
Later in
I'm getting TypeScript error:
I know that I can do explicit check using
How this situation can or should be handled without disabling TS compiler checks?
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?
Solution
This feature is called "strict null checks", to turn it off ensure that the
However, the existence of
One way to fix this is to ensure that the values are never
See Ryan Cavanaugh's answer for an alternative option, though!
--strictNullChecks compiler flag is not set.However, 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.One way to fix this is to ensure that the values are never
null or undefined, for example by initialising them up front:interface SelectProtected {
readonly wrapperElement: HTMLDivElement;
readonly inputElement: HTMLInputElement;
}
const selectProtected: SelectProtected = {
wrapperElement: document.createElement("div"),
inputElement: document.createElement("input")
};See Ryan Cavanaugh's answer for an alternative option, though!
Code Snippets
interface SelectProtected {
readonly wrapperElement: HTMLDivElement;
readonly inputElement: HTMLInputElement;
}
const selectProtected: SelectProtected = {
wrapperElement: document.createElement("div"),
inputElement: document.createElement("input")
};Context
Stack Overflow Q#40349987, score: 198
Revisions (0)
No revisions yet.