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 🚀
TypeScript: any vs unknown vs Generics Explained
More Relevant Posts
-
🚀 Node.js is more than just JavaScript. Most developers use Node.js daily. But very few understand what happens when a request hits the server. How can a single-threaded runtime handle thousands of requests? The answer lies in: ⚡ libuv ⚡ The Event Loop ⚡ Express Middleware pipelines In my latest deep dive, I explain: ✅ How libuv gives JavaScript async superpowers ✅ The 5 phases of the Event Loop ✅ Why setImmediate matters for I/O tasks ✅ How the Express middleware pipeline actually works Once you understand this, you stop guessing how your backend works. You start designing systems better. Thanks to Hitesh Choudhary Sir, Piyush Garg, Jay Kadlag 📖 Read the full article: https://lnkd.in/dngtRqk6 #NodeJS #BackendDevelopment #JavaScript #ExpressJS #WebDevelopment
To view or add a comment, sign in
-
What to actually use instead of any in TypeScript. The problem is, any basically turns TypeScript back into JavaScript. It kills your autocomplete, disables type checking, and spreads through your codebase like a virus. So, what should you use when things get complicated? 1. Use unknown (The responsible sibling) Think of unknown as a safer any. You can assign anything to it, but TypeScript will strictly stop you from using its properties or methods until you explicitly check what it is (type narrowing). 2. Use Record<K, V> for dynamic objects Need an object where you don't know the exact keys yet? Don't just type data: any. Use Record<string, unknown>. You keep the flexibility of dynamic keys without losing your safety net. 3. Use Generics <T> for reusable logic Writing a helper function? Instead of accepting any and returning any, use a generic. It tells the compiler: "I don't know the exact type yet, but whatever goes in, comes out with the exact same shape." and Zod or Valibot for API responses If data is coming from the outside world, any is a ticking time bomb. Use a schema library at the boundary. It validates the data at runtime and automatically infers strict TypeScript types for you. TypeScript is an amazing tool, but you're paying a lot of setup tax just to write plain JavaScript if you abuse any. #TypeScript #WebDevelopment #Frontend #JavaScript #CleanCode #React #WebDev
To view or add a comment, sign in
-
-
This is one of the 𝗯𝗶𝗴𝗴𝗲𝘀𝘁 𝗰𝗵𝗮𝗻𝗴𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝗻 𝘆𝗲𝗮𝗿𝘀. It finally solves the long-standing issues with the Date API. Whenever I worked with dates in JavaScript, I always had questions like: • Why does the same date behave differently across timezones? • Why are months 0-based? • Why is date parsing so inconsistent? • Why do we need libraries like Moment.js or Day.js for basic things? Turns out, it’s not just us. The Date API has design limitations. Now JavaScript has introduced a new solution: 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗔𝗣𝗜. It brings: • Better timezone handling • Immutable and predictable behavior • Clear separation of date, time, and timezone • Cleaner and more modern API design I recently explored this and broke down the real issues with the Date API and how Temporal fixes them. Video link in the comments: Would love to know, what’s the most confusing thing you have faced while working with JavaScript Date? TELUSKO Navin Reddy Hyder Abbas Harsh Rawal Akshay Agarwal Gaurav Sharma Siddhartha Hazra Sushil Rawal #javascript #webdevelopment #frontend #programming #developers
To view or add a comment, sign in
-
-
Does understanding JavaScript internals actually matter in "real life"? 🤔 Yesterday, I got my answer. 😅 I was booking movie tickets with friends. Seats were filling FAST. 🎟️🔥 I hit “Pay Now”... and the app started loading. My instinct? Panic. "Did it hang? Should I click again?" 😰 But I stopped myself. I remembered the Event Loop. While I stared at the spinner, JavaScript was juggling: 💳 The Call Stack processing my click. 🌐 Web APIs handling the payment request in the background. ⚡ The Callback Queue waiting to push the success message back to the UI. Because JS is non-blocking, the UI stayed "alive" even while the data was in transit. If I had clicked again, I might have triggered a double-charge or a race condition. Two seconds later? ✅ Payment Successful. > Sometimes, great engineering is invisible. It’s not just about writing code that works; it’s about understanding why it doesn't break under pressure. Don't just learn the syntax. Learn the engine. 🔁✨ Check out the diagram below notice how the 'Priority Queue' handles the logic while the 'Callback Queue' keeps the UI ready for the next move. That’s the secret sauce! #JavaScript #React #JavaScriptDeveloper #ReactjsDeveloper #Frontenddevelopment #SoftwareEngineering #Fullstackdeveloper
To view or add a comment, sign in
-
-
🚀 **Node.js A–Z Guide for Developers** A complete beginner-to-advanced roadmap to master Node.js 💻 📌 **What is Node.js?** Node.js is a powerful JavaScript runtime built on Chrome’s V8 engine that lets you run JS on the server side. ⚡ Fast | 🔄 Asynchronous | 📡 Scalable --- 🔤 **A–Z Highlights:** 🅐 Architecture → Event-driven, non-blocking I/O 🅑 Buffers → Handle binary data 🅒 CommonJS → `require` & `module.exports` 🅓 Debugging → `node inspect` / Chrome DevTools 🅔 Event Loop → Core of async behavior 🅕 File System → Read/write files 🅖 Globals → `__dirname`, `process` 🅗 HTTP → Create servers 🅘 NPM → Package management 🅙 JSON → Parse & stringify 🅚 Keep Alive → Better performance 🅛 Logging → `console`, winston 🅜 Middleware → Express flow control 🅝 Modules → Built-in & custom 🅞 OS → System info 🅟 Path → File paths 🅠 Queue → Callback execution 🅡 REPL → Interactive shell 🅢 Streams → Efficient data handling 🅣 Timers → setTimeout/setInterval 🅤 URL → Parse URLs 🅥 V8 → JS engine 🅦 Worker Threads → CPU tasks 🅧 Express.js → Backend framework 🅨 Yarn → Alternative to npm 🅩 Zlib → Compression --- ⚡ **Advanced Topics:** 🔐 Auth (JWT, OAuth) 🌐 REST API & GraphQL 🔄 WebSockets 🧩 Microservices 🐳 Docker + CI/CD 📈 Scaling with PM2 --- 📁 **Best Practices:** ✔ Use `.env` ✔ Async/Await ✔ Error handling ✔ Input validation ✔ MVC pattern --- 🎯 **Why Learn Node.js?** ✅ Build REST APIs ✅ Real-time apps ✅ Scalable backend systems --- 💡 **Roadmap:** 1️⃣ JavaScript Basics 2️⃣ Node Core Modules 3️⃣ Express.js 4️⃣ Database 5️⃣ Auth & Deployment --- 🚀 Master Node.js = Become a Production-Ready Developer 💪 #NodeJS #JavaScript #Backend #WebDevelopment #MERN #Programming #Developers
To view or add a comment, sign in
-
𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? JavaScript is single-threaded, but it can handle asynchronous operations efficiently using the Event Loop. The Event Loop is a mechanism that allows JavaScript to perform non-blocking operations like API calls, timers, and file reading while still running on a single thread. Here’s how it works: 1️⃣ Call Stack – Executes synchronous JavaScript code. 2️⃣ Web APIs – Handles async operations like "setTimeout", "fetch", and DOM events. 3️⃣ Callback Queue / Microtask Queue – Stores callbacks waiting to be executed. 4️⃣ Event Loop – Continuously checks if the call stack is empty and pushes queued callbacks to the stack for execution. This architecture allows JavaScript to manage asynchronous tasks without blocking the main thread, making it ideal for building fast and scalable web applications. Understanding the Event Loop is essential for mastering Promises, async/await, callbacks, and performance optimization in JavaScript. #JavaScript #EventLoop #WebDevelopment #FrontendDevelopment #NodeJS #AsyncJavaScript #CodingInterview #SoftwareEngineering #FullStackDeveloper #LearnToCode
To view or add a comment, sign in
-
𝐀 𝐬𝐮𝐛𝐭𝐥𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐭𝐡𝐚𝐭 𝐜𝐚𝐧 𝐜𝐚𝐮𝐬𝐞 𝐫𝐞𝐚𝐥 𝐩𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 𝐢𝐬𝐬𝐮𝐞𝐬 Many developers assume 𝘗𝘳𝘰𝘮𝘪𝘴𝘦.𝘢𝘭𝘭 cancels the other operations when one fails. It doesn’t. await Promise.all([ fetchUser(), fetchPosts(), fetchComments() ]) If 𝘧𝘦𝘵𝘤𝘩𝘜𝘴𝘦𝘳() rejects immediately, 𝘗𝘳𝘰𝘮𝘪𝘴𝘦.𝘢𝘭𝘭 will reject as well. But the other promises 𝐤𝐞𝐞𝐩 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐢𝐧 𝐭𝐡𝐞 𝐛𝐚𝐜𝐤𝐠𝐫𝐨𝐮𝐧𝐝. That means your system might still: write logs hit external APIs update databases send events …even though the main operation already failed. JavaScript promises don’t support built-in cancellation. They start executing as soon as they’re created. In many real systems this matters more than people expect. That’s why in production code you often see patterns like: - 𝘈𝘣𝘰𝘳𝘵𝘊𝘰𝘯𝘵𝘳𝘰𝘭𝘭𝘦𝘳 for cancellable requests - 𝘗𝘳𝘰𝘮𝘪𝘴𝘦.𝘢𝘭𝘭𝘚𝘦𝘵𝘵𝘭𝘦𝘥 when partial results matter - or explicit orchestration for async workflows. Async code looks simple on the surface, but small details like this can shape the behavior of entire systems. JavaScript Mastery JavaScript Developer TypeScript React w3schools.com #JavaScript #TypeScript #SoftwareEngineering #Programming #FrontendDevelopment #AsyncProgramming #WebDevelopment
To view or add a comment, sign in
-
-
When I started working with APIs in React, async/await made the code much easier to understand. Instead of chaining multiple .then() methods, async/await lets us write asynchronous code in a way that looks more like normal synchronous code. In API calling, async is used to define a function that returns a promise, and await pauses the execution of that function until the promise is resolved. Example: const fetchUsers = async () => { try { const response = await fetch("https://lnkd.in/dDNE8kTr"); const data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error); } }; Here’s what happens: fetchUsers is an asynchronous function. await fetch(...) waits for the API response. await response.json() waits for the JSON data to be converted. try/catch helps handle errors gracefully. Why use async/await in React API calling? Cleaner and more readable code Easier error handling Better flow when working with multiple async operations Understanding async/await is a small step that makes a big difference in writing better React code. #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #API #AsyncAwait #Programming #Coding
To view or add a comment, sign in
-
𝗧𝗮𝗸𝗲 𝗬𝗼𝘂𝗿 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗸𝗶𝗹𝗹𝘀 𝗧𝗼 𝗧𝗵𝗲 𝗡𝗲𝗫𝗧 𝗟𝗲𝗩𝗲𝗟 TypeScript is now the standard for building robust JavaScript applications. But many developers only use the basic types. - string - number - boolean TypeScript's true power lies in its advanced type features. These features can prevent bugs and make your code more maintainable. Let's look at an example. You're working with a user object that can be in different states. - loading - authenticated - unauthenticated You can use discriminated unions to solve this problem. - type LoadingUser = { status: 'loading'; } - type AuthenticatedUser = { status: 'authenticated'; id: string; name: string; email: string; } - type UnauthenticatedUser = { status: 'unauthenticated'; } - type User = LoadingUser | AuthenticatedUser | UnauthenticatedUser; TypeScript now understands the relationship between status and properties. You can also use conditional types to create types that change based on conditions. - type IsString<T> = T extends string ? true : false; Mapped types let you create new types by transforming properties of existing types. - type Partial<T> = { [P in keyof T]?: T[P]; } Your challenge is to identify one place in your codebase where you're using optional properties to represent different states, and refactor it using discriminated unions. Share your experience in the comments below. Source: https://lnkd.in/gbZSMQTA
To view or add a comment, sign in
-
🚀JavaScript is single-threaded… yet Node.js handles thousands of concurrent requests. How? JavaScript is single-threaded. So how does Node.js handle thousands of asynchronous operations like file reads, database calls, timers, and network requests without blocking the application? While learning Node.js internals, I tried to break this down with a simple architecture diagram. JavaScript runs inside the V8 engine and executes code line by line using a single call stack. This means only one piece of JavaScript code runs at a time. But when operations like reading a file, making an API request, or starting a timer happen, Node.js doesn't block the main thread waiting for the result. Instead, these operations are delegated to another layer that interacts with the operating system and manages asynchronous tasks. Once the operation finishes, the result is placed in a queue and executed when the call stack becomes free. This is what makes Node.js capable of handling many concurrent operations efficiently. I drew the architecture to understand the flow: JavaScript (Call Stack) → Node.js APIs → Async I/O Layer → Operating System → Event Loop → Callback Execution Two questions for backend developers: 1: What library powers asynchronous I/O and the event loop in Node.js? 2: Which programming languages are used to build the V8 engine, Node.js runtime, and the async I/O layer behind it? Drop your answers in the comments. #NodeJS #JavaScript #BackendDevelopment #AsyncProgramming #EventLoop #WebDevelopment #Libuv #react #mern
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development