Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deconstruct a Promise with the expected value when it can throw an Error Typescript

I have a code that looks like this

interface A {
  properties: object
}

const asyncFunction = async (): Promise<A | Error> => {
  try {
    return await anotherAsyncFunction();
  } catch (err) {
    throw err;
  }
}

Then I want to deconstruct

const { properties = {}} = await asyncFunction();

But since asyncFunction can return either an A or an Error TS shows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Property ‘properties’ does not exist on type ‘Error | A’.

Is there a way to handle the Promise with multiple Types and the deconstruction?

>Solution :

Consider removing the | Error from the Promise typing. Normally, the error path should be a rejection. In that case your destructuring code would work fine.

If you require to pass an Error back in a success path then you will need to use a type guard to determine if your Promise success value is A or Error.

function isA(result: A | Error): result is A {
    return (<A>result)?.properties;
}

const result = await asyncFunction();
if (isA(result)) {
   const { properties } = result;
} else {
   const error = result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading