Open In App

TypeScript null and undefined Type

TypeScript, a popular programming language, is widely used for building scalable and robust applications. In this article, we’ll explore the null and undefined types, which represent the absence of a value or uninitialized variables.

Null Type

What is Null?

Example of Null in TypeScript:



In this example, we will create a function of gfg, that will accept string or null values and then print the result post-narrowing




function greet(name: string | null): void {
    if (name === null) {
        console.log("Hello, Guest!");
    } else {
        console.log(`Hello, ${name.toUpperCase()}!`);
    }
}
 
greet("GeeksforGeeks"); // Output: Hello, GEEKSFORGEEKS
greet(null); // Output: Hello, Guest!

Output:



[LOG]: "Hello, GEEKSFORGEEKS!" 
[LOG]: "Hello, Guest!"

Undefined Type

What is Undefined?

Example:

When strictNullChecks is turned off (which is the default behavior), TypeScript is more permissive with null and undefined, and they are treated as assignable to all types. This means you can assign null and undefined to any variable




let myVar: string = undefined;
let anotherVar: number = undefined;
 
console.log(myVar); // Output: undefined
console.log(anotherVar); // Output: undefined

Output:

undefined
undefined

Strict Null Checks

By default, TypeScript is more permissive with null and undefined. However, when the strictNullChecks option is enabled, variables and properties must be explicitly typed as either nullable or non-nullable.


Article Tags :