0

In Typescript, is there a way to describe the reject() call from a Promise, for the functions return type?

For example, I have a function, validate() that takes some JSON and checks it's valid. If it is, a resolve() is returned. Otherwise, a reject() is returned, with a simply object, containing the error(s).

Is there a way to describe the Promise<> return type, so that I know it can potentially fail and return the reject()?

A bit like PHP @throws annotation, so the IDE can help to indicate that the exception hasn't been handled.

This is not the same as Typescript Promise rejection type, as I am wanting to set the functions return type to describe that the function can result in a promise rejection being thrown (with the type of data inside them as a bonus)

Mr Pablo
  • 4,109
  • 8
  • 51
  • 104
  • what kind of error or object does the `validate()` function return? Can you define its rejection structure? – jkalandarov Feb 21 '23 at 13:48
  • @jkalandarov the `reject()` return inside `validate()` returns an object, `{errors: validationErrors}` where `validationErrors` is an array of JS Error objects. – Mr Pablo Feb 21 '23 at 14:34
  • How exactly isn't it the same as the linked duplicate? Of course a promise *can* be rejected, that's expected. You want to annotate what type the rejection result will have. That's exactly what the duplicate is about. If it's not, clarify what's wrong about my above description. – deceze Feb 21 '23 at 15:19
  • "*This is not the same as Typescript Promise rejection type*" - it is **exactly** the same. There is no way to signal this in the type signature. Every promise can be rejected, and with `any` kind of value. – Bergi Feb 21 '23 at 15:20

0 Answers0