javascriptnode.jstypescriptpromise

How to use promise.allSettled with typescript?


Typescript build is failing as it does not seem to like Promise.allSetttled even though I have set ts config comilerOptions with "lib": [ "ES2020.Promise" ],

It seems as though the response for promise.allSettled does not include result or reason.

When running typescript build I get the following error:

Property 'reason' does not exist on type 'PromiseSettledResult<IMyPromiseResult>'.

and

Property 'value' does not exist on type 'PromiseRejectedResult'.

My code block looks like this and as you can see, I am trying to access reason and result from eaech of the promises that get resolved.

const myPromise = async () : Promise<IMyPromiseResult> {
  return new Promise((resolve) => {
    resolve("hello world")
  })
}

const data = await Promise.allSettled([
  myPromise()
]);

const response = data.find(res => res.status === 'fulfilled')?.result;

if(!response) {
  const error = data.find(res => res.status === 'rejected')?.reason;
  throw new Error(error);
}

How can I update the Promise.allSettled declaration to include the correct interfaces?


Solution

  • Like Bergi mentioned TypeScript does not know if the type is PromiseFulfilledResult / PromiseRejectedResult when checking types.

    The only way is to cast the promise result. This can be done because you already verified that the resolved promise is either fulfilled or rejected.

    See this example:

    const myPromise = async (): Promise<string> => {
      return new Promise((resolve) => {
        resolve("hello world");
      });
    };
    
    const data = await Promise.allSettled([myPromise()]);
    
    const response = (data.find(
      (res) => res.status === "fulfilled"
    ) as PromiseFulfilledResult<string> | undefined)?.value;
    
    if (!response) {
      const error = (data.find(
        (res) => res.status === "rejected"
      ) as PromiseRejectedResult | undefined)?.reason;
      throw new Error(error);
    }