How to check null or undefined of an object in Typescript Example
- Admin
- Nov 29, 2023
- Typescript
In this blog post, I will take you to the following examples.
- Undefined or null check with if the conditional expression
- Typeguard null and undefined union check
- using Optional Chaining and nullish coalescing operators
- lodash/ramda isNil method You can check another post on Fix for Object is possibly null
checking null or undefined of an object in javascript
The condition uses to check null or undefined values in javascript.
Typescript is a superset of javascript with an extra feature, typing, and assertions, Every piece of code works in typescripts.
if(expression){
console.log('Not null')}
}
the expression must be evaluated to be true or false. an expression evaluated to false for the 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");
}
It 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 defines 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.
The typescript implements the same in the 3.7 version.
These both are checked for null and undefined values.
Optional Chaining operator:
The symbol is ?
, is used to check the account is null
or undefined
, It will return an 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 provide the isNil
method to check for defined or not
_.isNil(value);
return type true/false - true - for Nullish values, else false.
Accepts 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
Conclusion
To Sum up, Learned about object check is null or undefined in typescript in multiple ways.