×
☰ See All Chapters

null and undefined in typescript

Before understanding the null and undefined types in TypeScript, we should know undefined and null in JavaScript. Let us see what are undedfined and null in JavaScript.

null and undefined in JavaScript

The undefined value is a primitive value used when a variable has not been assigned a value. When you declare a variable through var and do not give it a value, it will have the value undefined.

var test;

console.log(test); //Prints undefined

console.log(typeof test); //Prints undefined

The null value is a primitive value that represents the null, empty, or non-existent reference. null is an assignment value. It can be assigned to a variable as a representation of no value. You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". 

var test = null;

console.log(test); //Prints null

console.log(typeof test); //Prints object

null and undefined in typescript

In typescript we can set the data type of the variable to undefined/null explicitly. Undefined and null are types and as well as values. When --strictNullChecks argument is used while TypeScript compiling, to assign undefined value, variable should be declared with undefined data type. To assign null value, variable should be declared with null data type. In JavaScript null and undefined can be assigned to nay variable --strictNullChecks switches to a new strict null checking mode.

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

Example

let x: number;

let y: number | undefined;

let z: number | null | undefined;

x = 1;  // Ok

y = 1;  // Ok

z = 1;  // Ok

x = undefined;  // Error

y = undefined;  // Ok

z = undefined;  // Ok

x = null;  // Error

y = null;  // Error

z = null;  // Ok

x = y;  // Error

x = z;  // Error

y = x;  // Ok

y = z;  // Error

z = x;  // Ok

z = y;  // Ok

typescript-null-and-undefined-type-0


All Chapters
Author