Search code examples
javascriptif-statementecmascript-6destructuring

Can I use destructuring somehow inside an if statement?


is there a way I could do something like this ?

if({color, size, shape} = this.props){
  console.log('Received all props!');
} else {
  console.log('There are some missing props');
}

I want to know if I received all needed data through my Component's props, and if not then throw an error.

It's for creating reusable components.


Solution

  • You could use default values:

    function missing(prop) {
        throw new TypeError(`there is a missing ${prop} property`);
    }
    
    …
    try {
      const {
        color = missing("color"),
        size = missing("size"),
        shape = missing("shape"),
      } = this.props;
      // use color, size, shape here
      console.log("Received all props!");
    } catch(err) {
      console.log(err.message);
    }
    

    To use an if statement, no you cannot use destructuring to produce a boolean whether all properties are there. Rather do something usual as

    if ("color" in this.props && "size" in this.props && "shape" in this.props) {
      console.log('Received all props!');
    } else {
      console.log('There are some missing props');
    }
    

    (or better yet, check for the type of the value that you expected)