Typescript check if undefined

How to Detect Null and Undefined in Your TypeScript Code

By Omari Thompson-Edwards Hey, I’m Omari! I’m a full-stack developer from the UK, with a passion for ReactJS. I’m an enthusiastic and hardworking junior developer, driven by a desire to learn and explore ideas. Published: 28 March 2023

Checking for null and undefined is a common task in TypeScript (and JavaScript in general), and there are several ways to do it. In this article, we’ll explore some of the most common techniques for checking null and undefined values in TypeScript.

Equals

const myValue = maybeNullOrUndefined(); if (myValue === null) console.log('Null!'); if (myValue === undefined) console.log('Undefined!');

You might notice I’ve used “===” here, which is the strict equality operator. The difference here is that “===” as a stricter operator, will specifically check for null or undefined. Let’s take a look at this function, which uses the regular equality operator “==” instead of the stricter variant:

function checkValue(value: number | null | undefined) < console.log(value); if (myValue == null) console.log('Null!'); if (myValue == undefined) console.log('Undefined!'); >checkValue(null); checkValue(undefined);

The normal, loose equality operator specifically handles this case. If one of the values on either side is null or undefined, if the other one is null or undefined, then they’re equal. In a lot of scenarios this might not matter, you might just be checking if a variable has a truthy value. In that case you can safely use the regular equality operator. You can also shorten your code, to something like:

function checkValue(value: number | null | undefined) < console.log(value); if (!myValue) console.log('Null or undefined (doesnt matter)'); >checkValue(null); checkValue(undefined);

But there is a difference between null and undefined, and you might want to handle that separately in some cases. Null often means something is specifically meant to have no value, whereas undefined tends to mean something hasn’t been given a value yet. An example might be something like if you’re using a function to fetch some data. Null might mean the search has been completed, but the data wasn’t found, whereas undefined might indicate that the fetch was never completed successfully.

Читайте также:  Php table td font color

Coalescing Operator

Another way to check for null or undefined is to use the nullish coalescing operator (??), which was introduced in TypeScript 3.7. This operator returns the left-hand side of the expression if it’s not null or undefined, and the right-hand side otherwise:

const var1 = null ?? 'Pick me!'; const var2 = undefined ?? 'Pick me1'; const var3 = 'Now pick me!' ?? 'Not me'; console.log(var1, var2, var3);
const username = fetchUsernameMightfail() ?? 'default_username';
const API_URL = process.env.API_URL ?? 'http://localhost:1707';

I.e. if we get API_URL as an environment variable, use that value, but otherwise default to the value on the right. As well as the null coalescing operator, you might also find the less commonly used Nullish coalescing assignment operator:

let var1 = null; var1 ??= 'Replacing null'; var1 ??= 'Wont pick me (var1 isnt null)'

In the example above, var1 starts off as null. The next assignment does store the string in var1, since var1 is null. Then since we have ‘Replacing null’ in var1 now, the next assignment gets skipped. This can be used to assign a value only if the variable is null. It’s less commonly seen, but you might still run into it.

Optional Chaining

Another shortcut TypeScript provides for checking for null or undefined is optional chaining. It’s used for accessing properties of an object that might be undefined or null. Let’s take this type:

const myUser: MyUser | null = getUser(); //TS18047: 'myUser' is possibly 'null'.

We get an error with this code, since unfortunately, our user might not exist. So we could use one of the approaches we’ve learnt before, and check beforehand:

myUser?.friends?.[0].delete(); myUser?.friends?.[0]?.friends?.[0].delete(); myUser?.friends?.[0]?.friends?.[0]?.friends?.[0].delete(); //etc

Conclusion

Thanks for reading! Checking for null and undefined values is an important task in TypeScript. By using the techniques we’ve gone over, you can ensure that your code behaves as expected even when dealing with null and undefined values. Remember to choose the technique that fits your code best, bearing in mind whether or not you need your code to discern between “null” and “undefined”. If you’re interested in further reading, why not delve further into the rest of TypeScript’s primitive types. If you liked this article, feel free to leave a comment below!

👋 Hey, I’m Omari Thompson-Edwards

Hey, I’m Omari! I’m a full-stack developer from the UK, with a passion for ReactJS. I’m an enthusiastic and hardworking junior developer, driven by a desire to learn and explore ideas.

Источник

How To Check For Undefined In TypeScript?

Tim Mouskhelichvili

In TypeScript, checking if a variable or argument is defined is one of the most common tasks. Luckily, it is simple to accomplish.

The easiest way to check for undefined in TypeScript is to use a condition check, like so:

typescriptconst myName: string | undefined; if (myName === undefined) < console.log('name is undefined'); >

This article will explain checking for undefined in TypeScript and answer some of the most common questions.

typescript check for undefined

In JavaScript, undefined is a primitive data type that can indicate that:

  • A variable is not initialized. (for example, when a developer tries to access a non-existing property of an object).
  • A variable has no assigned value to it.

How to check for undefined using an if statement?

To check for undefined , in TypeScript, just like in JavaScript, the developer can use a condition check, like so:

typescriptconst myEmail: string | undefined; if (myEmail === undefined) < console.log('email is undefined'); > else < console.log('email is defined'); >

In this example, we check if myEmail is equal to undefined and output the correct log.

How to check for undefined using falsy values?

Another option to check for undefined in TypeScript is to check for falsy values.

In JavaScript, falsy values are a list of values that return false in a boolean context.

Here is how to check if a constant is falsy in TypeScript:

typescriptconst myEmail: string | undefined; if (!myEmail) < console.log('email is undefined'); >

This code not only checks for undefined but also for other falsy values.

Other JavaScript falsy values include: false, 0, -0, 0n, », null, NaN.

The best Web Development course in 2023! 👉 Learn Web Development

How to check for undefined before calling a function?

In TypeScript, you can use the optional chaining operator to check if an object is undefined before calling a function.

Here is an example of how to do it:

typescriptconst myEmail: string | undefined; myEmail?.indexOf('abc');

In this example, if the myEmail constant is undefined , the indexOf function is never called (so the code doesn’t break).

How to provide a default fallback for undefined ?

TypeScript provides the nullish coalescing operator to help set a fallback for an undefined value.

Here is an example of how to do it:

typescriptlet myEmail = email ?? 'info@admin.com';

In this example, if the email variable is undefined , myEmail fallbacks to the default email.

Final thoughts

As you can see, checking for undefined in TypeScript is simple.

You just need to do a condition check, and voila.

typescript check for undefined

Here are other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Check for Undefined in TypeScript

Check for Undefined in TypeScript

  1. Undefined vs Null in TypeScript
  2. Strict Undefined Check in Typescript Using “===”
  3. Check Undefined in Typescript Using ==
  4. Check Null Instead of Undefined in TypeScript
  5. Check Undefined in Typescript at Root Level
  6. Juggling-Check for Undefined and Null in Typescript

This tutorial will demonstrate how a programmer could check undefined in TypeScript with various coding examples and situations. It not only just gives you an idea of checking undefined in TypeScript but also helps in differentiating between null and undefined. First, let us see the main difference between the undefined and null.

Undefined vs Null in TypeScript

Strict Undefined Check in Typescript Using “===”

In JavaScript, as well as in its extended form TypeScript, validating the variable using === will check the value its type as well as its value.

let userEmail:string|undefined;  if(userEmail===undefined)   alert('User Email is undefined'); >else  alert(`User Email is $userEmail>`); > 

The first line sets the data type of variable userEmail as either string or undefined. After setting the datatype, it validates the variable in the if condition. === in TypeScript will allow checking both the variable type as well as its value and performs the desired operation after the validation. If the userEmail is assigned with the string value, the output will be following:

Else if it is not assigned with the value, it will be undefined and will be detected first if checked and displays the output as:

Check Undefined in Typescript Using ==

Rather than using === for the undefined checking in TypeScript, you could also use == , which check only the value.

let userEmail:string|undefined;  if(userEmail==undefined)   alert('User Email is undefined'); >else  alert(`User Email is $userEmail>`); > 

This will generate the same output as above in the previous example.

Check Null Instead of Undefined in TypeScript

In TypeScript, you could also check undefined using null in the if condition in place of undefined; this will also return true if something is undefined plus will return true if null. It will be done using == in the condition because === checks both the type and value and will give an error because of the reason that null is not equal to undefined in type.

let userEmail:string|undefined;  if(userEmail==null)   alert('User Email is undefined'); >else  alert(`User Email is $userEmail>`); > 

If === is used, then the output will be below.

Check Undefined in Typescript at Root Level

If you use == at the root level for the undefined checking in TypeScript, and the variable is undefined, you get a ReferenceError exception and the whole call stack unwinds. So for the checking, if the variable is undefined or not at the root level, typeof is suggested.

let globalData:string|undefined;  if (typeof globalData == 'undefined')   alert(`globalData is $globalData>`); > 

This solution is suggested in the open-source book for TypeScript Basarat Typescript Deep Dive.

Juggling-Check for Undefined and Null in Typescript

As == only checks the value instead of the type, and if we use null in the if condition for undefined checking in TypeScript, it will execute the same operation for the null. So to avoid this, we use a Juggling check which will perform the desired operation on the desired type.

var variableOne: any; var variableTwo: any = null;  function typeCheck(x:any, name:any)   if (x == null)   console.log(name + ' == null');  >   if (x === null)   console.log(name + ' === null');  >   if (typeof x === 'undefined')   console.log(name + ' is undefined');  > >  typeCheck(variableOne, 'variableOne'); typeCheck(variableTwo, 'variableTwo'); 

The first if statement will be executed for both the undefined and the null , the second and third condition checks the type, and the matched type value does the given operation. This code performs both the undefined check and the null check in TypeScript.

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

Related Article — TypeScript Undefined

Источник

Оцените статью