TypeScript Reference ยท Utility Types
TypeScript PromiseLike<T> type
Reference for PromiseLike<T> in TypeScript: the minimal thenable interface, how it differs from Promise<T>, and where await and Promise.resolve accept it.
PromiseLike<T> describes anything with a then method: the smallest contract await and Promise.resolve need. A real Promise<T> is a PromiseLike<T>, but so is a custom thenable from an old library, a query builder, or a hand-written object.
It is useful in two places. As a parameter or return type it lets your API accept "promise-ish" values from any source. In generic code it shows up in the library signatures for Promise.resolve, Promise.all and the callbacks of then.
interface PromiseLike<T> { then<R1 = T, R2 = never>( onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: any) => R2 | PromiseLike<R2>) | null, ): PromiseLike<R1 | R2>; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
interface PromiseLike<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined, ): PromiseLike<TResult1 | TResult2>; }
| Name | Description |
|---|---|
T |
The type of the fulfilled value. |
onfulfilled |
Called with the value when the thenable succeeds. |
onrejected |
Called with the rejection reason (typed any) on failure. |
Returns: another PromiseLike for the result of whichever handler ran.
Edge cases:
PromiseLikehas nocatchorfinally. Use.then(undefined, handler)or convert withPromise.resolve(x)first.- The rejection reason is
any, notunknown, and you cannot rely on it being anError.
Usage notes
- Use
T | PromiseLike<T>for inputs that may be synchronous or asynchronous, thenawaitthem inside. - Prefer returning
Promise<T>from your own functions. It offers more methods, and callers can chaincatchandfinally. Awaited<PromiseLike<number>>isnumber: the unwrapping type treats both the same. See Awaited.- A common mistake is declaring a function as returning
PromiseLike<void>and then calling.catchon the result: it will not compile. asyncfunctions always return a realPromise, regardless of what theyreturnorawait.Disposable's async sibling usesPromiseLike<void>as the return type of[Symbol.asyncDispose], so either kind is accepted.