Async TypeScript
Type a Promise
Annotate what a promise resolves to with Promise<T>.
function wait(ms: number): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("done"), ms);
});
}
wait(10).then(console.log);
Use async and await
An async function always returns a Promise. Await unwraps the value with its type.
async function loadTitle(): Promise<string> {
return "TypeScript";
}
async function main() {
const title = await loadTitle();
console.log(title.toUpperCase());
}
main();
Handle failures
Wrap awaits in try/catch. Error values are often unknown.
async function safe() {
try {
await Promise.reject(new Error("boom"));
} catch (err: unknown) {
if (err instanceof Error) {
console.error(err.message);
}
}
}
Async typing tips
- Prefer
async/awaitover long.thenchains while learning - Type fetch wrappers to return interfaces you define
- Do not ignore rejected promises
- Remember
asyncfunctions return promises even if you return a plain value
Comments
One comment per signed-in account. Comments are saved with this page’s URL.