Checking for undefined in TypeScript
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 userEmail
sets the data type of the variable to string or undefined. After setting the data type, it if
validates 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 userEmail
a string value is assigned to , the output will be as follows:
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:
==
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.
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}`);
}
If used ===
, the output will be below.
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 ReferenceError
an 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}`);
}
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');
The first if
statement will be executed for undefined
and 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.
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.
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 中使用 try..catch..finally 处理异常
Publish Date:2023/03/19 Views:396 Category:TypeScript
-
本文详细介绍了如何在 TypeScript 中使用 try..catch..finally 进行异常处理,并附有示例。
在 TypeScript 中使用 declare 关键字
Publish Date:2023/03/19 Views:257 Category:TypeScript
-
本教程指南通过特定的实现和编码示例深入了解了 TypeScript 中 declare 关键字的用途。
在 TypeScript 中 get 和 set
Publish Date:2023/03/19 Views:971 Category:TypeScript
-
本篇文章演示了类的 get 和 set 属性以及如何在 TypeScript 中实现它。
在 TypeScript 中格式化日期和时间
Publish Date:2023/03/19 Views:276 Category:TypeScript
-
本教程介绍内置对象 Date() 并讨论在 Typescript 中获取、设置和格式化日期和时间的各种方法。
在 TypeScript 中返回一个 Promise
Publish Date:2023/03/19 Views:590 Category:TypeScript
-
本教程讨论如何在 TypeScript 中返回正确的 Promise。这将提供 TypeScript 中 Returns Promise 的完整编码示例,并完整演示每个步骤。