Null refers to a value that is either empty or a value that doesn’t exist. It’s on purpose that there’s no value here. TypeScript does not make a variable null by default. By default unassigned variables or variables which are declared without being initialized are ‘undefined’. To make a variable null, we must assign Null to it. Typescript uses null to represent variables that have an absence of values or no value assigned to them in short. Sometimes, while writing huge codes, one might get make such mistakes and they may lead to unwanted errors.
Example 1: Assigning null to values
Javascript
let str: string; // Prints undefined console.log(str); // Assigning 'null' to variable str = null ; console.log(str); |
Output:
undefined null
Example 2: We can not assign values of other types to variables of type null(except null and undefined).
We can not assign values of other types to a variable that is declared as a null type. only null and undefined can be assigned.
Javascript
let num1: null ; num1 = null ; // Displays null console.log(num1); num1 = undefined; // Displays undefined console.log(num1); num1 = 20; // Raises error in timescript compiler console.log(num1); |
Output: Output in typescript compiler:
error TS2322: Type '20' is not assignable to type 'null'. num1 = 20; ~~~~
Output after executing js file:
null undefined 20
The null can not be assigned to undefined type variables:
Javascript
let var1: undefined; // Assigning null to undefined type variable var1 = null ; console.log(var1); |
Output:
Type 'null' is not assignable to type 'undefined'.ts(2322)
Example 3: Checking if a variable is Null
Since the typeof operator returns an object, one can’t use it to check for null. As a result, you can use either the == (equals operator) or the === (equals operator) operators (strict equals operator).
In the below code we can see that typeof operator returns an object. when checked with ‘==’ (equals operator), it returns true when variable == null but it also returns true when null==undefined. but when we use strict equals operator ‘false’ is returned when null is compared with undefined.
Javascript
let variable: null ; variable = null ; // Returns object console.log( typeof variable); // True console.log(variable == null ); // True console.log(variable == undefined); // True console.log( null == undefined); // False console.log(variable === undefined); // False console.log( null === undefined); |
Output:
object true true true false false
If we want to avoid null values in our code we can use if loop to check.
if (variable !=null){}