Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 24 of 56 · Typescript

Async/Await with Types

Duration: 20 minutes

Async Functions

async function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function fetchData(): Promise<string> {
  await delay(500);
  return "done";
}

Return Types

function getNumber(): Promise<number> { /* … */ }

If you forget to await, the function returns a Promise<...> which may cause type mismatches.

Error Handling

async function safeFetch(url: string): Promise<string | null> {
  try {
    const r = await fetch(url);
    if (!r.ok) throw new Error(r.statusText);
    return await r.text();
  } catch (e) {
    console.error(e);
    return null;
  }
}

Parallel Await with Promise.all

async function loadAll(urls: string[]): Promise<string[]> {
  const promises = urls.map(u => fetch(u).then(r => r.text());
  return Promise.all(promises);
}

Info

When using Promise.all, the resulting type is inferred as an array of the individual promise results.

Previous: Working with JSON & External APIsNext: Promises & Generics