TypeScript with Async/Await and Promises
TypeScript can type Promises using the generic `Promise<T>` type, where T is the type of the value the promise eventually resolves to. This makes asynchronous code just as type-safe as synchronous code.
When you use `async` functions, TypeScript automatically wraps the declared return type in a Promise, and `await` unwraps a Promise back to its underlying value type inside an async function.
async function getUser(): Promise<User> {
return { name: "Ana", age: 30 };
}Typing Promises
A function that fetches a number asynchronously can be typed as `function getNumber(): Promise<number>`, telling callers exactly what type they'll receive once it resolves.
async/await with types
Inside an `async function`, using `await somePromise` gives you the resolved value with the correct type directly, without needing `.then()` callbacks.
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
console.log("Start");
await delay(100);
console.log("End");
}
run();Start
Enddelay returns a Promise<void>, and await pauses execution until it resolves.
interface User {
name: string;
}
async function fetchUser(): Promise<User> {
return { name: "Mia" };
}
async function show() {
const user = await fetchUser();
console.log(user.name);
}
show();Miaawait unwraps the Promise<User> to give a plain User value with full type safety.
Key points
- Promise<T> describes a promise that resolves with a value of type T.
- async functions automatically wrap their return type in a Promise.
- await unwraps a Promise to its resolved value type inside async functions.
- TypeScript keeps asynchronous code just as type-safe as synchronous code.
