Sub topic 1
Promise<T>: the type of a value that arrives later
A Promise<T> represents a value that is not available yet but is expected later. The type parameter T describes the value when the promise succeeds.
For example, Promise<string> means “a promise that will fulfill with a string.” It does not mean that the function returns a string immediately.
Prerequisites
You should already know basic TypeScript types, functions, generics, union types, and JavaScript promises with async and await.
The value inside the promise
A promise has three runtime states:
- Pending: the operation is still running.
- Fulfilled: the operation finished successfully and produced a value.
- Rejected: the operation failed with a reason.
TypeScript models the successful value, but it does not encode the rejected value in Promise<T>. The T only describes fulfillment.
Consider this declaration:
declare function loadName(): Promise<string>;
const name = await loadName();
// name is a stringBefore await, the expression has type Promise<string>. After await, the expression has type string. The promise is the container for the future result.
A useful way to read common promise types is:
| Type | Meaning after successful completion |
|---|---|
| `Promise<string>` | A string will be available |
| `Promise<User>` | A `User` object will be available |
| `Promise<string[]>` | An array of strings will be available |
| `Promise<void>` | The operation completes without a useful value |
Declaring and creating promises
Add the resolved type when a function returns a promise. This makes the function's contract clear and lets TypeScript check every return path.
async function fetchLength(url: string): Promise<number> {
const res = await fetch(url);
const text = await res.text();
return text.length;
}The return statement returns a number, but the function's declared return type is Promise<number>. The async keyword wraps the returned number in a promise.
You can also construct a promise directly. The type argument describes the value passed to resolve.
function delay(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
}This promise resolves with no value, so its type is Promise<void>. A promise constructor is useful when adapting an API that uses callbacks, timers, or event handlers. Do not use it around an operation that already returns a promise. Unnecessary wrapping can make control flow harder to follow.
Transforming promise values
then transforms the successful value and returns another promise. If the callback returns U, the result usually has type Promise<U>.
declare function getUserId(): Promise<number>;
const label: Promise<string> = getUserId().then((id) => `user-${id}`);The original promise produces a number. The callback converts that number to a string, so the new promise produces a string.
await performs the same type-level unwrapping in a more readable form:
async function getLabel(): Promise<string> {
const id = await getUserId();
return `user-${id}`;
}Both versions preserve the relationship between the input and output types. If the callback returns the wrong type, an explicit annotation exposes the mistake.
Common mistakes
A frequent error is treating a promise as its resolved value:
declare function getCount(): Promise<number>;
const count = getCount();
// count is Promise<number>, not numberUse await inside an async function:
async function showCount(): Promise<void> {
const count = await getCount();
console.log(count);
}Another mistake is declaring Promise<any>. The any type removes useful checking at the asynchronous boundary. Prefer the real result type, unknown for data that needs validation, or a generic type when the function preserves its caller's type.
Exercise
What is the type of result, and why? const result = Promise.resolve(42);
Show answer
result is Promise<number>. The promise fulfills with the number 42, so TypeScript infers number as its resolved type.