TypeScript Casting

🔁 TypeScript Casting (Type Assertions)
📌 Casting does not change the value at runtime
It only helps the TypeScript compiler understand your intent
1️⃣ Why Type Casting is Needed
Sometimes TypeScript cannot infer the correct type.
Casting fixes this:
2️⃣ as Syntax (Recommended ⭐)
✔ Clean
✔ Preferred in modern TypeScript
3️⃣ Angle Bracket Syntax
⚠️ Not allowed in .tsx (React) files.
4️⃣ Casting with DOM Elements (Very Common)
Without casting:
5️⃣ Casting unknown to a Specific Type
6️⃣ Casting Between Compatible Types
⚠️ Avoid double casting unless absolutely required.
7️⃣ Casting Arrays
8️⃣ Casting Objects
9️⃣ Unsafe Casting (Be Careful ❌)
📌 TypeScript trusts you blindly during casting.
🔑 Casting Summary
| Syntax | Use Case |
|---|---|
as Type | Recommended |
<Type> | Not for TSX |
| DOM Casting | HTML elements |
unknown → type | Safe casting |
| Double Cast | Avoid |
⭐ Best Practices
✔ Prefer type narrowing over casting
✔ Use casting only when you are sure
✔ Avoid casting from unrelated types
✔ Avoid excessive any + casting
