Could you help me understand why TS compiler doesn't complain about this statement?
Promise.reject().catch(() => 5)
If checking the definition of the handler function inside the catch we can see the piece of code as follows:
interface Promise<T> {
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
It assumes that the handler function returns TResult | PromiseLike<TResult> where TResult = never. And then in my example a handler function returns 5 which is a number. So I could assume that 5 is never | PromiseLike<never>. But it is not the case. A number doesn't have .then function so it's not a PromiseLike.
Thanks!
TResultis inferrednumber, so it's actuallynumber | PromiseLike<number>, and5is assignable to that type. If you have an editor with language support, you should hover over thecatchcall to see what the types are.TResultjust defaults toneveraccording to that signature. It’s not constrained to it. It’s the difference between=andextends.extendsand=. I wasn't aware of it