JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

Checking for undefined in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

This article will demonstrate how programmers can check for undefined in TypeScript using various coding examples and situations. It not only gives you an understanding of checking for undefined in TypeScript, but also helps in differentiating between null and undefined. First, let's look at the main differences between undefined and null.

Undefined and null values ​​in TypeScript

Like JavaScript, and its extension TypeScript, there are two underlying types: null and undefined. They are both intended to define different things.

  • Not initialized: undefined.
  • Currently unavailable: null.

===Using strict undefined checks in Typescript

In JavaScript and its extension TypeScript, using ===validation variables will check the type of a value and its value.

let userEmail:string|undefined;

if(userEmail===undefined)
{
    alert('User Email is undefined');    
}else{
    alert(`User Email is ${userEmail}`);
}

The first line userEmailsets the data type of the variable to string or undefined. After setting the data type, it ifvalidates the variable under the condition. The in TypeScript ===will allow checking the variable type and its value and perform the required action after validation. If userEmaila string value is assigned to , the output will be as follows:

TypeScript execution output

Otherwise, if it has not been assigned a value, it will be undefined, and if checked it will be detected first and displayed as output:

TypeScript execution outputs undefined

==Check for undefined in Typescript using

In addition to using ===to check for undefined in TypeScript, you can also use ==, which only checks for values.

let userEmail:string|undefined;

if(userEmail==undefined)
{
    alert('User Email is undefined');    
}else{
    alert(`User Email is ${userEmail}`);
}

This will produce the same output as in the previous example.

unstrictchecktypescript

Checking for Null in TypeScriptUndefined

In TypeScript, you can also use null instead of undefined in if condition to check for undefined; this will also return true if something is undefined and true if it is null. It will be ==done using in the condition because ===checks the type and value and will give an error due to the fact that null is not equal to undefined in the type.

let userEmail:string|undefined;

if(userEmail==null)
{
	alert('User Email is undefined');    
}else{
    alert(`User Email is ${userEmail}`);
}

TypeScript null undefined

If used ===, the output will be below.

nullundefinedtypescript

Check for undefined in Typescript at the root level

If you use ==undefined check in TypeScript at the root level and the variable is not defined, you will get ReferenceErroran exception and the entire call stack is unwound. So for checking, it is recommended to use if the variable is not defined or not at the root level typeof.

let globalData:string|undefined;

if (typeof globalData == 'undefined') 
{
  alert(`globalData is ${globalData}`);
}

type

This solution is suggested in the open source book TypeScript Basarat Typescript Deep Dive.

Checking for undefined and Null values ​​in TypeScript

Since ==only the value is checked and not the type, if we use null in the if condition for undefined check in TypeScript, it will do the same thing for null. So, to avoid this, we use Juggling check which will do the desired action for the desired type.

var variableOne: any;
var variableTwo: any = null;

function typeCheck(x:any, name:any) {
    if (x == null) {
        console.log(name + ' == null');
    }

    if (x === null) {
        console.log(name + ' === null');
    }

    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}

typeCheck(variableOne, 'variableOne');
typeCheck(variableTwo, 'variableTwo');

Final Output

The first ifstatement will be executed for undefinedand null, the second and third conditions check the type, and the matching type value performs the given action. This code performs undefined check and null check in TypeScript.

Previous: None

Next:Using jQuery and TypeScript

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Handling exceptions with try..catch..finally in TypeScript

Publish Date:2025/04/15 Views:170 Category:TypeScript

This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow

Convert JSON object to a class in TypeScript

Publish Date:2025/04/15 Views:80 Category:TypeScript

Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript. TypeScript provides the abili

Update TypeScript to the latest version using NPM

Publish Date:2025/04/15 Views:119 Category:TypeScript

This article provides a guide to update to the latest version of TypeScript using npm, which is the best and most popular method used by developers. This also gives us an in-depth look at what npm is and why to use it. Node Package Manager

Using jQuery and TypeScript

Publish Date:2025/04/15 Views:148 Category:TypeScript

This article provides the basic understanding and concepts of using jQuery with TypeScript. It guides on how to use jQuery in TypeScript through a coding example and outputs using various methods in TypeScript and provides knowledge about w

在 TypeScript 中返回一个 Promise

Publish Date:2023/03/19 Views:590 Category:TypeScript

本教程讨论如何在 TypeScript 中返回正确的 Promise。这将提供 TypeScript 中 Returns Promise 的完整编码示例,并完整演示每个步骤。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial