Async Functions in TypeScript
Async Functions in TypeScript
Section titled “Async Functions in TypeScript”Basic Async Function
Section titled “Basic Async Function”async function fetchUser(id: string): Promise<User> { const response = await fetch(`/api/users/${id}`); return response.json();}
// Arrow async functionconst fetchUsers = async (): Promise<User[]> => { const response = await fetch("/api/users"); return response.json();};Promise Types
Section titled “Promise Types”// Promise type parameterstype PromiseResult<T> = T extends Promise<infer U> ? U : T;
type Result = PromiseResult<Promise<string>>; // stringtype Direct = PromiseResult<number>; // number
// Promise all with typed resultsconst [user, posts] = await Promise.all([ fetchUser("1"), fetchPosts("1"),] as const);// user: User, posts: Post[]Error Handling
Section titled “Error Handling”// Try-catch with unknown errorasync function safeFetch<T>(url: string): Promise<T | null> { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); } catch (error) { if (error instanceof Error) { console.error(error.message); } return null; }}Interview Questions
Section titled “Interview Questions”Easy: How do you type an async function’s return value?
Medium: What type does Promise.all return?
Hard: How would you type a function that returns a Promise with a discriminated union?