简体   繁体   中英

Typescript: what's the difference between checking if a variable is empty vs. checking if it has a value?

I'm adding validation to my code and, to improve readability, wrote the following:

  if (!uid) {
    return {result: 0, message: 'You are not authorized.'}
  }

The alternative would be to check if the variable exists:

  if (uid) {
    //do some code
  }

However, if I have a lot of different variables to validate, I don't like having to nest them like so:

  if (uid) {
     if (otherVar) {
        //do some code 
     } else {
        //else code 1
     }
  } else {
     //else code 2
  }

Is there any difference to doing method 1 vs method 2?

The answer:

  • Method 1 only checks for the value in that variable . If a value exists / evaluates to true , then it will return true .
  • Method 2 checks for variables after you have finished the first check and it returns true .

My opinion , you don't actually have to do it like that. Instead, you can use optional chaining operator in order to make safe checks inside an object. For example:

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name; // notice the usage of '?'
console.log(dogName); // will return 'undefined' as 'dog' object does not exist in that object.

Quoting MDN Docs:

The?. operator functions similarly to the. chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

From there, you can use optional chaining in order to simplify your nested blocks - like using a global error handler.

const result = uid?.otherVar?; // imagine 'otherVar' does not exist!

if (!result) return handleResult();

Further reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM