Skip to content
Advertisement

Typescript Promise rejection type

How do I set the type of the rejection of my promise? Let’s say I do:

const start = (): Promise<string> => {
   return new Promise((resolve, reject) => {
      if (someCondition) {
         resolve('correct!');
      } else {
         reject(-1);
      }
   });
}

Let’s say I want to reject with a number. But I cannot set the type; I can pass whatever I want to the reject here.

Moreover, when using this promise, I want to have compiling error if I use the rejection response type incorrectly.

Advertisement

Answer

As explained in this issue, Promise doesn’t have different types for fulfilled and rejected promises. reject accepts any argument that doesn’t affect type of a promise.

Currently Promise cannot be typed any better. This results from the fact that a promise can be rejected by throwing inside then or catch (this is a preferable way to reject existing promise), and this cannot be handled by typing system; also, TypeScript also doesn’t have exception-specific types except never.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement