In TypeScript 2, you can use the undefined type to check for undefined values.
If you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable uemail is undefined like this:
if(uemail === undefined)
{
}
Answer from ashish on Stack OverflowIn TypeScript 2, you can use the undefined type to check for undefined values.
If you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable uemail is undefined like this:
if(uemail === undefined)
{
}
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');
Hi, all, I often do stuff like this in my code, to check for a variable being not null and not undefined.
// check if value is not null and not undefined
if (value) {
...
}However, I'm now thinking this can leads to bugs, because of 0, "", false and NaN also being falsy.
What is a better way to check a variable is not null and not undefined? I could use this I think, wondering if there is something shorter than this:
if (typeof value !== 'undefined' || value !== null) {
...
}Is there a standard function to check for null, undefined, or ...
How do you check if a variable is undefined in TypeScript? I am looking for ways to resolve typescript check if undefined - LambdaTest Community
Good way to check for variable being not null and not undefined.
Typescript not acknowledging 'not undefined' assertion
Videos
function notEmpty(value){
return (typeof value !== 'undefined' && value.trim().length);
}
it will also check white spaces (' ') along with following:
- null ,undefined ,NaN ,empty ,string ("") ,0 ,false
Will return false only for undefined and null:
return value ?? false