Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript signature of Promise#catch onrejected handler

I notice the standard typing for Promise#catch in es6-shim.d.ts is defined as

interface Promise<T> {
  catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
  catch(onrejected?: (reason: any) => void): Promise<T>;
}

I am wondering why this is written this way, instead of as

catch(onrejected?: (reason: any) => T | PromiseLike<T> | void): Promise<T>;

Some other file es6-promise.d.ts by Nate Archibald gives a single signature of

catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>;

not referring to <T> at all.

So is the second overloaded signature in es6.shim-d-ts, which as far as I know is in heavy use in a compile-to-ES5 environment, unnecessary/undesirable?


1 Answers

Well, T can be void which means your use case is already supported.

If you did T | PromiseLike<T> | void the output might have been a Promise<string> that's resolved with void which would be a type error.

Note that promises aren't statically typed in a strong way in these definitions. The signature is actually harder since reason is typed any. This is like most languages (like C#) that sport unchecked exceptions and unlike Java and Swift which feature checked exceptions (a part of the signature of a function is what it might throw).

like image 148
Benjamin Gruenbaum Avatar answered Oct 20 '25 00:10

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!