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');
Videos
What do you prefer to check for null and undefined?
Feel free to comment on why which one is better.
This code do not work at all, but not sure why.
type IsUndefined<T> = T extends undefined ? 1 : 0;
For example:
type IsTypeUndefined = IsUndefined<number | undefined>; // This returns: 1 | 0
Is there a way for check if a type is undefined in a conditional?
Update: For simplicity, I replicated the original error with simpler code.
Update 2: I got around this by using a type guard for T. Thank u/ritajalilip for the suggestion. I still think Typescript should handle this better though.
As you can see on the screenshot, inside the if statement I'm asserting that x is not undefined. However Typescript is failing to acknowledge and still thinks that x can be undefined.
Any idea of what's going on?