Differentiating undefined from null

While  typeof returns the undefined string when performing against an undefined type, it returns object against null. This inconsistency becomes an issue when you forget which case can use typeof by performing the wrong operation for the wrong no type type. However, undefined and null do not require the use of typeof to do a type check. It is possible to compare directly the variable against undefined or  null:

let g: number | undefined = undefined;
let h: number | undefined | null = null;
console.log(typeof g); // undefined
console.log(typeof h); // object
console.log(g === undefined); // true
console.log(g === null); // false
console.log(h === undefined); // false
console.log(h === null); // true

In a situation where a variable can be undefined or null or any other primitive, the best way is to check for the nullability of the type and carry on with further type comparisons.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.181.146