Open In App

TypeScript null and undefined Type

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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?

  • null represents the intentional absence of any object value.
  • It’s often used to signify that a variable or object property does not reference any valid object or value.

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

Javascript




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?

  • undefined indicates that a variable has been declared but hasn’t been assigned any value.
  • It’s commonly used to represent missing function arguments or uninitialized object properties.

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

Javascript




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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads