Looking at a this type declaration:
export interface Thenable<R> {
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>
}
I'm aware of what it does. I can do something like this:
type MessagesSendResponse = ...
export const announce = (options: sendParameters):Thenable<MessagesSendResponse> => {
return Promise.all([emailMessage(options),smsMessage(options)]
}
This makes it smart enough to know that in context
const val1 = announce(..)
that val1 is a Thenable/Promise whereas in this context
const val2 = await announce(..)
val2 is of type MessagesSendResponse
My question is that I don't understand the following about the Thenable interface:
What does it mean to say
Thenable<U>I understand thatUis a generic type, yet what doesThenable<U>mean? What's another way to write that?Somehow this definition is saying that a function returns a thenable / promise that in turn returns a generic. Yet both the interface type and the return value for both
thenandcatchare of typeThenable<U>. It looks like its saying that it returns itself, which I suppose is right since a thenable can return another thenable, but how does it know that it know that the resolution isMessagesSemdResponseif it says it returnsThenable<U>? Is there some build in feature in the IDE for this?
I realize question 2 reflect my confusion. Any links to references appreciated, I couldn't find anything similar to this pattern.
part1:
we are defining generic interface with one type parameter
Rpart2:
it has method
then, which takes two parametersonFulfilledandonRejected, and the method itself is generic - it depends on another type paramererU.part3, the most interesting one:
onFulfilledis declared with this type:it means that it's either a function taking
Rand returningU, or anotherThenable<U>Here is a relationship between
RandU: if you haveThenable<R>, it'sthenmethod accepts a callback which is called with a value of typeR(the one that original thenable produced), and should returnU. Or it can accept anotherThenable<U>.The return value of this
thenmethod, then, isThenable<U>.In short, this is how chaining of promises is described with types.