Monday, March 16, 2020

Typescript Example - Ways of Checking null or undefined of an object in - using Typeguard

checking null or undefined of an object in typescript 

 In this blog post, I will take you to the following examples

Typescript Example - Ways of Checking null or undefined of an object in - using Typeguard
  • Undefined or null check with if conditional expression
  • Typeguard null and undefined union check
  • using Optional Chaining and nullish coalescing operators
  • lodash/ramda isNil method 

checking null or undefined of an object in javascript

 In javascript, If the condition is used to check null or undefined values Typescript is a superset of javascript with an extra feature, typing, assertions, Every piece of code works in typescripts.

if(expression){
console.log('Not null')}
the expression must be evaluated to true or false an expression evaluated to false for below values
null
empty string spaces- ""
undefined
NAN - Not number zero
false.
Let's see an example
if ( obj !== 'undefined' && obj !== null ) {
console.log('Object is Not Null');
}
This works in javascript and typescripts.
Let's see an example of doing the same thing with type guards in typescripts.

Typeguard null and undefined union check Typescript 2.x

 isNullOrUndefined function is defined with accepting object type, null types are added as Union type with type guard syntaxes and return boolean values.

function isNullOrUndefined<T>(object: T | undefined | null): object is T {
  return <T>object !== undefined && <T>object !== null;
}

let obj=null;

console.log(isNullOrUndefined(obj)); //false
let obj1=123;
console.log(isNullOrUndefined(obj1)); //true

using Optional Chaining and nullish coalescing operators 

Optional Chaining and nullish coalescing operator are introduced in ES11, Typescript also implemented the same in 3.7 version. These both are check for null and undefined values Optional Chaining operator ? is used to checking the account is null or undefined, It will return id if an account is not null or undefined, else return undefined
let account={
id:1}
let deparmentid=account?.id?
console.log(deparmentid)
lets an example on nullish coalescing operators

let account=null;
let deparmentId=account??.id
console.log(deparmentId)
if an account is not null or undefined, returns id, else returns account

JQuery null or undefined

To check in javascript or jquery , use typeof operator.
typeOf checks objects, returns undefined if the object is undefined or null

if(typeof obj == "undefined"){
 console.log('Object is null');
}

lodash/ramda isNil method 

 lodash and rambda provides isNil method to check for defined or not
_.isNil(value)
return type true/false - true - for Nullish values, else false
Accets object to check for nullish values let's see an example
let obj;
console.log(_.isNil(null))//true
console.log(_.isNil(false))//false
console.log(_.isNil(obj))//true

Related article


EmoticonEmoticon