Search code examples
ecmascript-6destructuring

Destructuring Different Conditional Return Types


I have a function that will return either a string, if there is an error, or two objects, when there is no error. My function looks like this:

function logResults(json) {
  const one = json[0]
  const two = json[1]
  const error = json[0].error

  if (error) {
    return 'error at logResults' // string type
  }

  return (one, two) // object type
}

My question is would it possible to destructure this function's return types? This line works if two objects are successfully returned: let [ one, two ] = logResults(json), but it won't work if a string is returned. If destructuring is not possible, what is the most efficient way to handle the different return types?


Solution

  • return either a string, if there is an error, or two objects, when there is no error

    Uh, don't do that. For exactly the reasons you have demonstrated: the function becomes unusable. Just throw an error or return an array with the two objects.

    function logResults(json) {
      const [one, two] = json;
      if (one.error) {
        throw new Error('error at logResults');
      }
    
      return [one, two]; // or just `json`?
    }
    

    Now you can use destructuring after the call as you imagined.