How to check undefined in Typescript
I am using this code to check undefined variable but it's not working.
var uemail = localStorage.getItem("useremail");
if (typeof uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
Solution 1:
In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable z is undefined as:
if(uemail === undefined)
{
}
Solution 2:
You can just check for truthy on this:
if(uemail) {
console.log("I have something");
} else {
console.log("Nothing here...");
}
Go and check out the answer from here: Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Hope this helps!
Solution 3:
From Typescript 3.7 on, you can also use nullish coalescing:
let x = foo ?? bar();
Which is the equivalent for checking for null or undefined:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
While not exactly the same, you could write your code as:
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
Solution 4:
It's because it's already null or undefined. Null or undefined does not have any type. You can check if it's is undefined first. In typescript (null == undefined)
is true.
if (uemail == undefined) {
alert('undefined');
} else {
alert('defined');
}
or
if (uemail == null) {
alert('undefined');
} else {
alert('defined');
}