1

Say I have the following code:

function fn(): Promise<string> {
  return new Promise((resolve, reject) => {
    let randomBit = (Math.random() * 10) % 2 === 0;

    if (randomBit) {
      resolve("Resolve");
    } else {
      reject(0);
    }
  });
}

The above method, which returns a valid Promise, is correctly typed as Promise<string>. I understand that the internal type declares the type returned in the case of a successful resolution. But, what about the return of a rejection? In my example the rejection would resolve to number. Shouldn't, the return signature of fn() be something like

Promise<string, number>

?

Or, more generally, shouldn't a Promise declare the generic types for the two possible outcomes, like

Promise<TSuccess, TError>

?

I feel like I'm missing something.

seebiscuit
  • 4,905
  • 5
  • 31
  • 47
  • I think the accepted answer for this question https://stackoverflow.com/questions/50071115/typescript-promise-rejection-type answers your question. See the second paragraph there. – Ian Dec 30 '20 at 20:19
  • The function always returns a promise. That promise may then resolve or reject. So, there's no "return of a rejection". There's always a return of a promise that, then sometime later, may resolve or reject. The syntax is declaring that if it resolves, it will resolve with a string. A rejection works like throwing an exception which can't be typed by TypeScript because that's a run-time occurence, not something the static code analysis of typescript can necessarily track. – jfriend00 Dec 30 '20 at 20:19
  • It does @Ian! Excellent explanation. Considering deleting this question... – seebiscuit Dec 30 '20 at 20:21
  • 2
    @seebiscuit don't worry about deleting it - leaving it closed as a duplicate is better for helping people discover the other answer in the future – Ian Dec 30 '20 at 20:22

0 Answers0