How to check undefined in Typescript

Typescript

Typescript Problem Overview


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

Typescript Solutions


Solution 1 - Typescript

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 - Typescript

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 3 - Typescript

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: https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in

Hope this helps!

Solution 4 - Typescript

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

Solution 5 - Typescript

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.

Solution 6 - Typescript

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.

Solution 7 - Typescript

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 undefined for 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/2021 As 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.

Solution 8 - Typescript

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.

Solution 9 - Typescript

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
}

Solution 10 - Typescript

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

Solution 11 - Typescript

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.

Solution 12 - Typescript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpushpView Question on Stackoverflow
Solution 1 - TypescriptashishView Answer on Stackoverflow
Solution 2 - TypescriptPaulus PotterView Answer on Stackoverflow
Solution 3 - TypescriptMotonstronView Answer on Stackoverflow
Solution 4 - TypescriptNabin Kumar KhatiwadaView Answer on Stackoverflow
Solution 5 - TypescriptLucasView Answer on Stackoverflow
Solution 6 - TypescriptSam SegersView Answer on Stackoverflow
Solution 7 - TypescriptmtholenView Answer on Stackoverflow
Solution 8 - TypescriptEzioView Answer on Stackoverflow
Solution 9 - TypescriptFDiskView Answer on Stackoverflow
Solution 10 - TypescriptSukhminder SandhuView Answer on Stackoverflow
Solution 11 - TypescriptWillem de VriesView Answer on Stackoverflow
Solution 12 - TypescriptAryan DixitView Answer on Stackoverflow