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');
}
1

12 Answers

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)
{
}
2

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();

While not exactly the same, you could write your code as:

var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
1

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!

11

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'); }
2

Adding this late answer to check for object.propertie that can help in some cases:

Using a juggling-check, you can test both null and undefined in one hit:

if (object.property == null) {

If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

if (object.property === null) {

Typescript does NOT have a function to check if a variable is defined.

Update October 2020

You can now also use the nullish coallesing operator introduced in Typescript.

let neverNullOrUndefined = someValue ?? anotherValue;

Here, anotherValue will only be returned if someValue is null or undefined.

It actually is working, but there is difference between null and undefined. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.

For more information about the difference between the both of them, see this answer.

For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) { //some function
}

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefinedfor example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) { //some function
}

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') { //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

Edit: 07/2021As many have pointed out, in TypeScript it is not possible anymore to redefine undefined and therefore you will be less likely to have this risk. But in older browsers and if using pre ECMA 5 JS then there is still this risk.

5

NOT STRICTLY RELATED TO TYPESCRIPT

Just to add to all the above answers, we can also use the shorthand syntax

var result = uemail || '';

This will give you the email if uemail variable has some value and it will simply return an empty string if uemail variable is undefined.

This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.

I know that this is not optimal and strange example, but good to know that there is yet another way to check if some value is defined using JSON.stringify

const foo = '';
const buzz = null;
const fooBuzz = 0;
const array = [];
let declared;
const asUndefined = undefined;
if (JSON.stringify(foo)) { console.log(foo); // empty string
} else { console.log('undefined');
}
if (JSON.stringify(buzz)) { console.log(buzz); // null
} else { console.log('undefined');
}
if (JSON.stringify(fooBuzz)) { console.log(fooBuzz); // 0
} else { console.log('undefined');
}
if (JSON.stringify(array)) { console.log(array); // []
} else { console.log('undefined');
}
if (JSON.stringify(asUndefined)) { console.log(asUndefined);
} else { console.log('undefined'); // undefined
}
if (JSON.stringify(declared)) { console.log(declared);
} else { console.log('undefined'); // undefined
}

"typescript": "^3.7"

 const uemail = undefined; if (uemail ?? false) { alert('defined'); } else { alert('undefined'); }

Protect from null & undefined

 const uemail = null; if (uemail && (uemail ?? false)) { alert('defined or not null'); } else { alert('undefined or null'); }

I had the following piece of code (state is a json object):

const value: string = state[identifier].description; // undefined
const severity: string = state[identifier].level; // undefined

That gave the following error:

Uncaught TypeError: (intermediate value)[identifier] is undefined

I solved it by using the Nullish Coalescing Operator in combination with Optional chaining.

const value: string = state[identifier]?.description ?? "Undefined"; // "Undefined"
const severity: string = state[identifier]?.level ?? "Undefined"; // "Undefined"

No need for if-checks or typeof equations.

Use 'this' keyword to access variable. This worked for me

var uemail = localStorage.getItem("useremail");
if (typeof this.uemail === "undefined")
{ alert('undefined');
}
else
{ alert('defined');
}
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like