As with JavaScript, nullish values in TypeScript include null and undefined values. They both have special meanings and often require different treatments in our applications. Continue reading to find out how to check for undefined in TypeScript.
Check For Undefined In TypeScript
With Regular if Statements
The most straightforward solution is to compare a variable with the undefined value, which is a valid comparison in TypeScript with the equals operator. When the operation returns true, we know that that variable is indeed undefined.
The following example demonstrates how you can implement this simple idea:
let string1: string;
let string2: string;
string1 = 'Tutopal';
if (string1 == undefined)
{
console.log('string1 is undefined.');
}
else
{
console.log('string1 is not undefined.');
}
if (string2 == undefined)
{
console.log('string2 is undefined.');
}
else
{
console.log('string2 is not undefined.');
}
Output:
string1 is not undefined.
string2 is undefined.
In the above program, we declare two number variables but only assign a value to one of them. This means the second variable automatically has the undefined value.
We use two if-else statements to check whether those variables equal the undefined value and print a message accordingly.
There is a way to shorten this comparison, thanks to the fact that the undefined value is falsy in TypeScript. Like values like 0, NaN, null, and false, undefined always gets coerced and evaluated like the false value.
With this knowledge, you have another way to check any variable against the undefined value:
let string1: string;
let string2: string;
string1 = 'Tutopal';
if (!string1)
{
console.log('string1 is undefined.');
}
else
{
console.log('string1 is not undefined.');
}
if (!string2)
{
console.log('string2 is undefined.');
}
else
{
console.log('string2 is not undefined.');
}
Output:
string1 is not undefined.
string2 is undefined.
Since string1 doesn’t have the undefined value, (!string1) evaluates in the same way as false. Likewise, string2 is undefined, meaning (!string2) acts like the true value.
Remember that being falsely doesn’t mean the undefined value equals false:
console.log(undefined == false);
Output:
false
With Nullish Coalescence
In JavaScript and TypeScript, the nullish coalescing operator (??) can create a one-line statement to check if a value is null or undefined.
Syntax:
leftExpr ?? rightExpr
This logical operator will return the right-hand side expression if the left-hand side expression equals undefined or null. Otherwise, it returns the value of the left-hand side expression.
You can rewrite the if-else statements with these operators to check for the undefined value. It comes in handy when you need to perform this check and throw an error message when running into the undefined value:
let string1: string;
let string2: string;
string1 = ‘Tutopal’;
console.log(string1 ?? “String is null or undefined.”);
console.log(string2 ?? “String is null or undefined.”);
Output:
Tutopal
String is null or undefined.
We use the nullish coalescing operation inside the console.log() method with both variables as the left-hand side operands. As the string variable is neither null nor undefined, it returns the value of that variable to the method. Meanwhile, because string2 is undefined, the console.log() method is given the “String is null or undefined.” string (which is the right-hand side operand).
With Optional Chaining
Another JavaScript feature that has great support on TypeScript is the optional chaining operator (?.). You can use it to check for undefined properties of TypeScript objects.
This operator can reach values of properties located in an object chain without requiring every reference is valid. When encountering nullish values (null or undefined, it doesn’t create an error. Instead, the optional chaining operator just returns undefined.
Example:
type Site = {
name: string;
properties?: {
URL: string;
rank: number;
type?: string;
};
};
let Tutopal: Site = {
name: “Tutopal”
};
const type = Tutopal.properties?.type;
console.log(type)
Output:
undefined
The above example creates a Site object and sets its name property. However, properties and type haven’t been assigned to any value. As a result, the optional chaining operator returns undefined, which the console.log() method prints to the output. You can then, for instance, fix an undefined property.
Summary
You can use the equals, nullish coalescence, or optional chaining operators to check for undefined in TypeScript. Choose the solution depending on how you plan to process the result of the check.
Reference source
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html