15. Modules & API Integration
Structuring Large Projects & Fetching Data
You cannot keep all your interfaces in one massive file. Real applications use Modules to separate types. Furthermore, real applications rely heavily on external APIs. You must understand how to strictly type asynchronous operations and network responses.
Modules: Exporting and Importing Types
Just like you export JavaScript functions, you can export TypeScript Interfaces and Types to share them across your project.
Typing APIs: The Promise Wrapper
When you fetch data from an API, the data does not arrive instantly. The function returns a Promise. In TypeScript, you must explicitly declare that the function returns a Promise, and then specify the shape of the data that the Promise will eventually resolve into using generics: Promise<T>.
Typing the Fetch API
The native fetch() API is completely untyped by default (it returns Promise<any>). You must explicitly type the parsed JSON response.
Knowledge Check
Ready to test your understanding of 15. Modules & API Integration?