Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Kousha Avatar asked Apr 27 '18 22:04

Kousha


1 Answers

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.

like image 166
Estus Flask Avatar answered Sep 28 '22 06:09

Estus Flask