TypeScript: any vs unknown vs Generics Explained

any vs unknown vs Generics in TypeScript Most developers know these exist. Very few know when to use which. Let’s break it down clearly 👇 🔴 1️⃣ any — The TypeScript Killer let value: any = "Hello"; value.toFixed(); // ✅ No error Why ? --> Because any disables type checking. No safety. No IntelliSense. No protection. 👉 any = “Trust me bro.” Use it too much… You’re back to JavaScript. 🟡 2️⃣ unknown — The Safe any let value: unknown = "Hello"; value.toUpperCase(); // ❌ Error TypeScript says: “Prove what it is first.” You must narrow it: if (typeof value === "string") { value.toUpperCase(); // ✅ Safe } ✔ Type-safe ✔ Forces validation ✔ Best for external/unsafe data 👉 unknown = “I don’t know yet — prove it.” 🟢 3️⃣ Generics — Flexible AND Safe function identity<T>(value: T): T { return value; } Now: const result = identity("Hello"); result.toUpperCase(); // ✅ result.toFixed(); // ❌ Type is preserved. Flexible. Reusable. Fully typed. 👉 Generics = “I don’t know the type yet, but I’ll preserve it.” 🧠 Core Difference:-> Feature | any | unknown | GenericType safety-> |❌ None | ✅ Yes | ✅ Yes Requires narrowing->| ❌ | ✅ | ❌ Preserves type info -> | ❌ | ❌ | ✅ Best for -> | Quick hacks | External data | Reusable logic 🎯 When To Use What? ✔ Use any → Rarely (migration, temporary fixes) ✔ Use unknown → API responses, user input, unsafe data ✔ Use Generics → Libraries, reusable functions, scalable systems 💎 Senior Developer Insight any - avoids the problem. unknown - forces you to handle the problem. Generics - solve the problem elegantly. That’s the maturity ladder in TypeScript. Be honest… How often do you still reach for any? 👀 Let’s discuss 👇 #TypeScript #JavaScript #FrontendDevelopment #CleanCode #SoftwareEngineering #WebDevelopment #LearnInPublic #ReactJS 🚀

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories