TypeScript provides strong type checking for asynchronous operations using Promise<T>, typed async/await functions, and async data fetchers.
flowchart LR
A["async function fetchData(): Promise<User>"] --> B["Returns Promise<User>"]
B --> C["await unwraps Promise -> returns User"]
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
interface UserProfile {
id: string;
name: string;
email: string;
}
// Typed Async Function returning Promise<ApiResponse<UserProfile>>
async function fetchUserProfile(userId: string): Promise<ApiResponse<UserProfile>> {
// Simulating async network delay
await new Promise((resolve) => setTimeout(resolve, 100));
if (userId === "invalid") {
throw new Error("User not found");
}
return {
status: 200,
message: "Success",
data: {
id: userId,
name: "Alex Mercer",
email: "[email protected]"
}
};
}
// Consuming typed async function
async function runDemo(): Promise<void> {
try {
const response = await fetchUserProfile("usr_9901");
console.log(`Fetched User: ${response.data.name} (${response.data.email})`);
} catch (error) {
if (error instanceof Error) {
console.error(`Fetch failed: ${error.message}`);
}
}
}
runDemo();
async function returns a raw value 5, its return type signature is automatically wrapped as Promise<number>.unknown: In strict TypeScript, catch (err) types err as unknown. Use instanceof Error narrowing before accessing err.message.Promise.all with Typed Arrays: await Promise.all([fetchA(), fetchB()]) returns a strongly typed tuple of resolved values.Write an async function signature fetchCount(): Promise<number> that resolves to 42.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With