Home > OS >  Is there more elegant way to return boolean indicating that a variable has been set in Typescript
Is there more elegant way to return boolean indicating that a variable has been set in Typescript

Time:08-07

I'm curious as to know the simplest way to check if a variable has been set. Consider this class:

class MyObject {
  myVar: string;
}

I can easily check if the above variable is not set like this:

isMyVarNotSet(obj: MyObject): boolean {
  return !obj.myVar;
}

but unfortunately, the reverse doesn't work so well.

isMyVarSet(obj: MyObject): boolean {
  return obj.myVar;
}

Typescript thinks that I'm trying to return the string version of myVar (for good reason) instead of checking if a variable has been set.

I can write some more code to get around it like this:

isMyVarSet(obj: MyObject): boolean {
  if(obj.myVar) {
    return true;
  }
  return false;
}

But that seems verbose.

As an alternative, I can write it with double negative like this:

isMyVarSet(obj: MyObject): boolean {
  return !!obj.myVar;
}

Althought the double negative is the shortest, and arguably the simplest solution. But this feels wrong. Not to mention, it will look strange and confusing at first look.

I'm wondering if there is something else in typescript has that I'm not aware that solves this problem more elegantly.

CodePudding user response:

You can always use a ternary operator.

isMyVarSet(obj: MyObject): boolean {
  return obj.MyVar ? true : false;
}

I think this improves readability.

CodePudding user response:

Use the method hasOwnProperty() to check if the property exists in the object and then check if it is not equal to null or undefined.

isMyVarSet(obj: MyObject): boolean {
  return (obj.hasOwnProperty('MyVar') && obj.MyVar != null);
}

  • Related