Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  84] [ 6]  / answers: 1 / hits: 70019  / 6 Years ago, fri, april 27, 2018, 12:00:00

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.


More From » typescript

 Answers
23

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.


[#54554] Tuesday, April 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;