Promise<T> — Type-Safe Async with TypeScript
Promise — Type-Safe Async with TypeScript
💡 Why Learn This? — One Step Beyond JS Promises
Promise — Pinning the Type of the 'Resolved Value' with Generics
What Is the T in Promise?
A JS Promise is 'an object that promises a value arriving later.' A TS Promise
What Changes When T Is Pinned?
In plain JS, pizza.toFixed(2) would pass compilation → TypeError at runtime → caught by tests if you are lucky, or it blows up in production if you are not.
An async Function's Return Type Is Automatically Wrapped in Promise
Any function with the async keyword always returns a Promise. Therefore you must write Promise<...> as the return type (or leave it to inference).
Explicit Types vs. Inferred Types
In practice you use both:
Promise.all Infers Down to Tuple Types
In JS, even if you receive the result array, the type of each element is unknown. TS preserves the type at each position.
💡 💡 Key Differences: JS ↔ TS
1. Always pin <T> on new Promise()
2. It is better to explicitly annotate the return type of async functions
Public API functions should reveal their intent just from the signature.
3. Receive the result of Promise.all as a tuple
4. The error in catch is unknown (TS 4.4+)
5. Write a generic helper once and use it forever