Sub topic 1
Promise<T>: the type of a value that arrives later
Prerequisites
This chapter assumes you can:
- Read and write basic TypeScript types, functions, and interfaces.
- Use generics at the level of
Array<T>and simple generic functions. - Use JavaScript promises and
async/awaitsyntax at a basic level. - Use union types and narrow them with checks such as
typeofandinstanceof.
Examples assume "strict": true in tsconfig.json and a target of ES2017 or later, so the Promise type and async functions are available.
What the type says
A Promise<T> is an object that stands for a value of type T that may not exist yet. The T is the type of the value you get when the operation succeeds. It says nothing else.
const later: Promise<number> = new Promise((resolve) => {
setTimeout(() => resolve(42), 100);
});later is not a number. It is a container that will hold a number once the timer fires. The compiler treats the container and its contents as different types, and most mistakes with async code come from mixing them up.
At runtime a promise is in one of three states:
- Pending: the operation has not finished.
- Fulfilled: the operation succeeded and the promise holds a value.
- Rejected: the operation failed and the promise holds a reason.
A promise settles once. After it moves from pending to fulfilled or rejected, it never changes again.
The diagram shows what the type leaves out. T describes only the fulfilled branch. The rejected branch has no type parameter, so a Promise<number> can reject with an Error, a string, or any other value. Later chapters cover how to handle that. For now, remember that the compiler tells you what success looks like and nothing about failure.
Reading a Promise<T> annotation
You will meet Promise<T> in three places: as a variable type, as a function return type, and as a parameter type.
declare function getName(id: number): Promise<string>;
const nameLater: Promise<string> = getName(1);
function logLater(p: Promise<string>): void {
p.then((value) => console.log(value.toUpperCase()));
}
logLater(nameLater);Inside the then callback, value is a string, because then unwraps the promise for the callback. Outside the callback, you hold a Promise<string>, and string methods are not available on it.
The type argument can be any type, including unions, objects, arrays, and void:
| Type | Meaning | Column |
|---|---|---|
| `Promise<string>` | Eventually a string | |
| `Promise<string \ | null>` | Eventually a string or `null`, such as a lookup that may find nothing |
| `Promise<User[]>` | Eventually an array of users | |
| `Promise<void>` | Eventually finishes, with no useful value | |
| `Promise<never>` | Never fulfills. It can only reject or stay pending |
Promise<void> is the usual type for "do this, tell me when it is done". It is not the same as Promise<undefined>, though the two behave alike in practice.
The most common error: using the container as the value
Forgetting to unwrap a promise is the mistake you will see most often. The compiler catches most forms of it.
declare function getName(id: number): Promise<string>;
function shout(): string {
const name = getName(1);
return name.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'Promise<string>'.
}The error message names the type, Promise<string>. When you see a Promise<...> in an error where you expected the inner type, you have a missing await or .then.
A second form is a condition that is always true. A promise object is always truthy, even if it will resolve to false:
declare function isAdmin(id: number): Promise<boolean>;
function check(id: number): void {
if (isAdmin(id)) {
// Error: This condition will always return true since this
// 'Promise<boolean>' is always defined.
console.log("admin");
}
}With strictNullChecks on (part of strict), TypeScript reports this directly in if conditions. The check is limited, though. A promise used in &&, in a ternary, or passed to a function that accepts unknown or any may not be flagged. The linter rules covered in a later chapter close those gaps.
A third form is a wrong return type. A function declared to return string cannot return a Promise<string>:
declare function getName(id: number): Promise<string>;
function lookup(id: number): string {
return getName(id);
// Error: Type 'Promise<string>' is not assignable to type 'string'.
}You cannot fix this by changing the body to return a plain string, because the work really is asynchronous. The fix is to change the return type to Promise<string>. This is the main rule of async typing: once a function depends on a promise, its own result is a promise too. The callers have to change as well, and that is how async types spread through a codebase.
How then changes the type
The then method takes a callback and returns a new promise. TypeScript computes the new type from what the callback returns:
declare function getCount(): Promise<number>;
const doubled: Promise<number> = getCount().then((n) => n * 2);
const label: Promise<string> = getCount().then((n) => `count: ${n}`);
doubled.then((n) => console.log(n));
label.then((s) => console.log(s));The callback returns a number, so the result is Promise<number>. The callback returns a string, so the result is Promise<string>.
If the callback returns a promise, the result is flattened. You never get a promise of a promise:
declare function getCount(): Promise<number>;
declare function getName(id: number): Promise<string>;
const name: Promise<string> = getCount().then((n) => getName(n));
// Not Promise<Promise<string>>.
name.then((s) => console.log(s.length));This matches runtime behavior. A promise that resolves with another promise adopts that inner promise's outcome. The type system mirrors it, so Promise<Promise<string>> is almost never what you want. If you do see one, a value was probably wrapped by hand and something upstream is wrong. The Awaited<T> chapter covers how TypeScript computes this flattening.
Typing the failure branch with catch
The catch method returns a promise whose type is the union of the original type and whatever the handler returns:
declare function getCount(): Promise<number>;
const safe: Promise<number> = getCount().catch(() => 0);
const maybe: Promise<number | string> = getCount().catch(() => "unavailable");
safe.then((n) => console.log(n.toFixed(1)));
maybe.then((v) => console.log(v));The handler's parameter is typed any in the standard library, so the reason is not checked. Declare it yourself as unknown if you want to be forced to narrow it: .catch((reason: unknown) => ...). The next chapters return to this, because it connects to why catch blocks give you unknown.
Assignability between promise types
Promise<T> is covariant in T. If A is assignable to B, then Promise<A> is assignable to Promise<B>:
declare const exact: Promise<"ready">;
const wide: Promise<string> = exact;
// The reverse fails:
// const narrow: Promise<"ready"> = wide;
// Error: Type 'Promise<string>' is not assignable to type 'Promise<"ready">'.
wide.then((s) => console.log(s));This is the same rule as for arrays and other read-only containers. It lets you pass a more specific promise where a general one is expected.
Promise<unknown> accepts any promise. This is useful for helpers that only care when something finishes:
async function waitFor(p: Promise<unknown>): Promise<void> {
await p;
}Parameters typed Promise<unknown> or Promise<void> behave differently. A Promise<number> is assignable to Promise<unknown>, but it is not assignable to Promise<void> in an annotation. If you want "any promise", use unknown.
Promise.resolve and Promise.reject
Two static helpers create promises that are already settled. They are handy in tests and when a function must return a promise but already has the value:
const ready: Promise<number> = Promise.resolve(7);
const nothing: Promise<void> = Promise.resolve();
const failed: Promise<never> = Promise.reject(new Error("no data"));
ready.then((n) => console.log(n));
nothing.then(() => console.log("done"));
failed.catch((e: unknown) => console.log(e instanceof Error ? e.message : e));Promise.resolve(7) infers Promise<number>. Promise.reject(...) infers Promise<never>, because it can never produce a value. Since never is assignable to every type, a Promise<never> fits wherever any Promise<T> is expected.
PromiseLike and thenables
The standard library also defines PromiseLike<T>, an interface with only a then method. Any object with a compatible then is called a thenable. Some libraries return thenables that are not real promises, such as certain query builders. await and Promise.resolve accept them.
For your own function parameters, prefer Promise<T> unless you have a reason to accept thenables. Return types should be Promise<T>, so callers can use catch and finally, which PromiseLike does not have.
A worked example
This function combines the ideas above. It takes a promise, transforms it, and falls back on failure:
interface User {
id: number;
name: string;
}
declare function fetchUser(id: number): Promise<User>;
function displayName(id: number): Promise<string> {
return fetchUser(id)
.then((user) => user.name.trim())
.catch(() => "Unknown user");
}
displayName(1).then((name) => console.log(`Hello, ${name}`));The types trace as follows:
fetchUser(id)isPromise<User>..then((user) => user.name.trim())givesPromise<string>..catch(() => "Unknown user")givesPromise<string | string>, which simplifies toPromise<string>.- The function's declared return type,
Promise<string>, matches.
The function is not marked async. It returns a promise because it hands back the chain it built. The next chapter shows how async changes the way you write and type this.
Summary of rules
Promise<T>is a container.Tis the type of the fulfilled value only.- You cannot use the value inside without
awaitorthen. - A function that returns a promise must declare
Promise<T>, and so must its callers if they pass the result on. thenreturns a promise typed from its callback, and flattens a returned promise.catchwidens the type to a union with the handler's return type.Promise<T>is covariant, andPromise<never>fits anywhere.
Exercise
Given declare function getScore(): Promise<number>;, what are the types of a and b in const a = getScore().then((n) => n > 10); and const b = getScore().then((n) => Promise.resolve(String(n)));?
Show answer
a is Promise<boolean>, because the callback returns a boolean. b is Promise<string>, not Promise<Promise<string>>, because then flattens a promise returned from its callback.
Exercise
This code fails to compile. Why, and what is the smallest change that fixes it without using await?
declare function isOnline(): Promise<boolean>;
function status(): string {
if (isOnline()) {
return "online";
}
return "offline";
}
Show answer
isOnline() returns a Promise<boolean>, which is always truthy, so the condition tests the container instead of the boolean. The function also returns string although its answer depends on a promise. Change the return type to Promise<string> and return isOnline().then((online) => (online ? "online" : "offline")).
Exercise
What is the type of const p = Promise.reject(new Error("x"));, and why can you assign it to a variable of type Promise<string>?
Show answer
It is Promise<never>. never is assignable to every type and Promise<T> is covariant in T, so Promise<never> is assignable to Promise<string>.