TypeScript Modules and Async
Learn how to organize TypeScript code into modules, use namespaces, handle asynchronous operations with Promises and Async/Await, manage errors and share functionality using imports and exports.
1. Introduction to Modules and Async
In real-world applications, code is divided into separate files so that functions, classes and types can be maintained and reused easily. TypeScript modules provide this structure through imports and exports.
Asynchronous programming is useful when an application waits for an operation such as an API request, a timer or other I/O operation. Promises and Async/Await help write and manage this code.
Example: Asynchronous Operation
function getStudent(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Rahul");
}, 1000);
});
}
async function displayStudent(): Promise<void> {
const name = await getStudent();
console.log("Student: " + name);
}
displayStudent();
Expected Output
Student: Rahul
The Promise resolves after approximately one second. The await keyword waits for its result inside the asynchronous function before displaying the student's name.
2. Modules and Async Workflow Diagram
This diagram illustrates how application modules and asynchronous operations work together.
Modules
Organize code into reusable files and components.
Import / Export
Share functions, classes and types across modules.
Async Operation
Perform an operation that completes later.
Result / Error
Process the result or handle a failure.
3. Topics Covered in This Module
Learn each topic step by step with explanations, TypeScript code examples, expected outputs and visual diagrams.
1. Modules
Understand how to divide code into separate files and reuse functions, classes and types.
Key concepts: Module scope, reusable files and module organization.
2. Namespaces
Group related declarations under a named scope and understand how namespace members are exposed.
Key concept: The namespace keyword.
3. Promises
Learn how asynchronous operations represent results that may become available in the future.
Key concepts: Pending, fulfilled, rejected, then, catch and finally.
4. Async/Await
Write asynchronous code in a readable style using async functions and await expressions.
Key concepts: async,
await and Promises.
5. Error Handling
Handle exceptions and asynchronous failures so an application can respond appropriately.
Key concepts: try, catch, finally and rejected Promises.
6. Import and Export
Share and reuse declarations across module files using named exports, default exports and imports.
Key concepts: import,
export and module paths.
4. Understanding Promise States
A Promise represents the eventual completion or failure of an asynchronous operation. It begins in the pending state and then becomes fulfilled or rejected.
Pending
The operation has not settled yet.
Fulfilled
The operation completed successfully and produced a result.
Rejected
The operation failed and has a rejection reason.
5. Why Use Async/Await?
Async/Await makes Promise-based code easier to read, especially when several asynchronous operations must run in sequence.
Example
function getCourse(): Promise<string> {
return Promise.resolve("TypeScript");
}
async function displayCourse(): Promise<void> {
const course = await getCourse();
console.log("Course: " + course);
}
displayCourse();
Expected Output
Course: TypeScript
An async function returns a Promise. The await expression obtains the fulfilled value when the Promise fulfills, or throws if the Promise rejects.
6. Introduction to Async Error Handling
Asynchronous operations can fail. Using try/catch with await lets the application respond to a rejected Promise without leaving the failure unhandled in the function.
Example
async function loadStudent(): Promise<void> {
try {
throw new Error("Student not found");
} catch (error) {
if (error instanceof Error) {
console.log("Error: " + error.message);
}
}
}
loadStudent();
Expected Output
Error: Student not found
The catch block handles the thrown error. In real applications, similar handling is used for failed API requests, invalid responses and other asynchronous failures.
7. Where Are Modules and Async Used?
Web Application Architecture
Organize components, models, utilities and services in separate files.
API Integration
Wait for HTTP requests and process responses using Promises and Async/Await.
Reusable Utilities
Export common helper functions and import them wherever needed.
Error Management
Handle failed operations gracefully and show meaningful error messages.
Summary
Modules organize code into reusable files. Namespaces group related declarations under a named scope. Promises represent asynchronous outcomes, Async/Await simplifies asynchronous workflows, and try/catch handles errors. Imports and exports allow selected functionality and types to be shared between modules.
Next, learn how to organize TypeScript modules and reuse declarations across different files.