How to declare the TypeScript Promise rejection type
Spoiler alert: It isn't possible.
Consider a utility function that returns a rejected Promise.
export function rejectWithNumber(n: number): Promise<number> {
return Promise.reject(n);
}
This compiles, but the return type declaration isn’t correct.
In
Promise<T>
,T
is the fulfillment type. The rejection type is alwaysany
.
So what’s the correct return type declaration for the function?
export function rejectWithNumber(n: number): Promise<any> {
return Promise.reject(n); ^^^^^^^^^^^^
}
This is a little confusing, though.
This function doesn’t return a Promise<any>
because the rejection type is always any
. It returns a Promise<any>
because it doesn’t know what the Promise’s fulfilled type is. Only the calling function knows.
It’s not possible to declare the TypeScript Promise rejection type. It’s always any
.
Comments
-
Join the conversation for this post on GitHub Dicussions. Thanks for your feedback 🎉
Sources