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

Time:05-06

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

Property 'properties' does not exist on type 'Error | A'.

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

CodePudding user response:

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;
}
  • Related