Synchronous vs Asynchronous — TypeScript Protects Even Callback Signatures
Synchronous vs Asynchronous — TypeScript Protects Even Callback Signatures
💡 Why Should You Learn This? — Sync and Async Are the Same, but the Safety Net Is Different
Sync and Async Behave the Same, but Callback Types Differ
1. Runtime Behavior Is Identical
Whether you use TS or JS, this behavior is identical. TypeScript compiles away the types and runs as JavaScript.
2. The Difference Is Explicit 'Callback and Return Type' Annotations
3. Pin the Return Type of Async Functions
4. The Return Value of setTimeout Differs by Environment — One Approach Is Only Safe in One Environment
> 💡 When building libraries or general-purpose modules, always use ReturnType<typeof setTimeout>. You can write number or NodeJS.Timeout directly only in app code where the environment is fixed.
💡 💡 Key Differences: JS vs TS (Sync/Async)
1. For functions that accept a callback, embed the callback signature in the parameter type
2. For async functions, annotate the return type in the signature
3. Accept timer IDs as ReturnType<typeof setTimeout>
Browsers return number, Node returns NodeJS.Timeout — this is safe regardless of environment.
4. Don't let async results leak as any
The default return type of res.json() is Promise<any>. The key is to pin types at the boundary — either by casting or narrowing with a validation library like zod.
5. Callback hell has the same answer in both JS and TS: async/await
TypeScript provides even better inference support for async/await. This was already covered in the Promise lesson.