🚫 any is TypeScript's escape hatch. And most of us use it way too often. Every time you type any, you're telling TypeScript: "Stop helping me here." Here are the 4 types I reach for instead 👇 1. unknown — the safe version of any When you don't know the type upfront (API responses, JSON parsing), use unknown. It forces you to narrow the type before using it. TypeScript keeps protecting you. 2. never — for exhaustive checks Use it in switch statements to catch unhandled cases at compile time. If you add a new union member and forget to handle it, TypeScript errors immediately — not in production. 3. Record<K, V> — for typed dictionaries Instead of { [key: string]: any }, write Record<string, User>. Now your values are typed and your IDE actually helps you. 4. Union types A | B — enumerate what's valid Don't loosen the type — enumerate exactly what's allowed. type Status = 'loading' | 'success' | 'error' is infinitely better than string. The rule I follow: → If the type is truly uncertain → unknown → If a case should never happen → never → If it's a key-value map → Record<K,V> → If it's one of N values → union type any has maybe 2 legitimate use cases. Everything else has a better option. Which of these do you find yourself using most? 👇 #TypeScript #JavaScript #WebDevelopment #CleanCode #Frontend
Samir Telrandhe’s Post
More Relevant Posts
-
I spent months writing async Node.js code without really understanding it. Then a production bug taught me the event loop the hard way. Here's what you need to know: Node.js is single-threaded — but it handles thousands of concurrent requests without freezing. How? The event loop. It has 4 key parts: 1. Call Stack — Your sync code runs here, line by line. One thing at a time. 2. libuv Thread Pool — Async tasks (file I/O, HTTP requests) get offloaded here. Your code keeps running. 3. Microtask Queue — Promise callbacks live here. They run BEFORE anything else queued. 4. Macrotask Queue — setTimeout and setInterval callbacks wait here. This explains a classic JS gotcha: console.log('1') setTimeout(() => console.log('2'), 0) Promise.resolve().then(() => console.log('3')) console.log('4') Output: 1 → 4 → 3 → 2 The Promise fires before the setTimeout — even with a 0ms delay. Once you understand this, a whole category of async bugs just... disappears. What part of async JavaScript tripped you up most? Drop it below 👇 #NodeJS #JavaScript #WebDevelopment #SoftwareEngineering #FullStack
To view or add a comment, sign in
-
-
Honest opinion: I resisted TypeScript for longer than I should have. “It’s just extra syntax.” “It slows me down.” “JavaScript is fine.” I was wrong. Here’s what changed my mind - working on a large banking application with 10+ developers. Without TypeScript: ∙ Props getting passed incorrectly across components ∙ API response shapes being assumed, not enforced ∙ Bugs that only showed up in production With TypeScript: ∙ Errors caught before the code even runs ∙ Components become self-documenting ∙ Refactoring feels safe instead of scary The “slowdown” in writing types saves 10x the time in debugging. If you’re still on the fence about TypeScript — just try it on one project. That’s all it takes. What made you finally switch to TypeScript? 👇 #TypeScript #ReactJS #Frontend #WebDevelopment #JavaScript
To view or add a comment, sign in
-
-
When I first switched from JavaScript to TypeScript, I did what most devs do: I just added types everywhere and called it a day. ❌ type name = string type age = number type user = any ← this was my biggest mistake Using "any" completely defeats the purpose of TypeScript. You're just writing JavaScript with extra steps. Here's what changed everything for me: 🔹 Use "unknown" instead of "any" — it forces you to handle types safely 🔹 Use Union types to model real-world data: type Status = 'active' | 'inactive' | 'pending' 🔹 Use "as const" to lock down literal values and stop magic strings 🔹 Let TypeScript INFER types when it can — don't over-annotate 🔹 Use Utility Types (Partial<T>, Pick<T>, Omit<T>) — they save hundreds of lines The moment I stopped fighting TypeScript and started thinking in types, my code quality jumped overnight. TypeScript isn't just about catching bugs. It's about making your intent clear to every developer who reads your code after you. What's the one TypeScript trick that levelled you up? 👇 #TypeScript #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #MERN #CleanCode
To view or add a comment, sign in
-
🚀 Understanding Node.js Internals: Event Loop & Thread Pool This week, I took a deeper dive into how Node.js actually works behind the scenes — and it completely changed how I think about asynchronous code. 🔹 JavaScript in Node.js runs on a single thread 🔹 Yet it handles multiple tasks efficiently using the Event Loop 🔹 Heavy operations are offloaded to the Thread Pool (via libuv) Some key takeaways: Event Loop manages execution in phases (Timers, I/O, setImmediate, etc.) setTimeout(0) is not truly immediate setImmediate() behaves differently inside vs outside I/O process.nextTick() runs before the event loop even starts Understanding these concepts makes async behavior much more predictable and helps write better backend code. Would love to hear your thoughts or corrections 🙌! Blog Link : https://lnkd.in/gxBA4DeT #JavaScript #WebDev #LearnInPublic #Blog #libuv #EventLoop #ThreadPool #ChaiCode Thanks to Hitesh Choudhary, Piyush Garg, Jay Kadlag, Akash Kadlag for guidance 😊
To view or add a comment, sign in
-
-
Callbacks looked simple… until they didn’t. While revisiting Node.js async concepts, I finally understood why “callback hell” is such a big problem. Here’s the journey in 3 steps: 1️⃣ Callbacks Used to handle async tasks like file reading, APIs, timers 2️⃣ The Problem Nested callbacks → messy code → hard to debug 3️⃣ The Solution Promises → cleaner, chainable, more readable This small shift completely changed how I look at asynchronous code. Sometimes revisiting basics gives the biggest clarity. FAQs: Q: What is a callback? A: A function passed into another function to run after a task completes Q: Why is callback hell bad? A: It creates deeply nested code that is hard to read, debug, and maintain Q: How do Promises help? A: They allow chaining and make async code cleaner and more structured #NodeJS #JavaScript #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
💡 TypeScript Truth: Why any Can Mislead You (and unknown Saves You) I ran into an interesting behavior while working with TypeScript 👇 let a: any = 10; let b: string = a; console.log(typeof a); // number console.log(typeof b); // number 😳 At first, this feels wrong. If b is a string, why is it still a number? 👉 Here’s the catch: TypeScript types only exist at compile time — not at runtime. So this line: let b: string = a; ❌ does NOT convert a into a string ✅ it only tells TypeScript to treat it as a string 🚨 The Problem with any any disables type checking completely: You can assign anything to anything TypeScript won’t stop you Bugs sneak into runtime 🔐 Safer Alternative: unknown let a: unknown = 10; // let b: string = a; ❌ Error TypeScript forces you to verify first: if (typeof a === "string") { let b: string = a; // ✅ Safe } ✅ If you actually want conversion: let b: string = String(a); 🎯 Key Takeaway any = "Trust me bro" 😅 unknown = "Prove it first" 🔍 Types don’t change values — they only check them As a MERN developer, switching from any → unknown can seriously improve code safety, especially when dealing with APIs. #TypeScript #WebDevelopment #MERNStack #JavaScript #FrontendDev #CleanCode
To view or add a comment, sign in
-
-
TypeScript won't save you from writing bad code. But it will make sure you can't hide it. I've seen teams migrate from JS to TS thinking it'll magically clean up their codebase. It doesn't. What it does — ruthlessly — is surface the mess that was already there. ────────────────────────────────── JS — no complaints: function getUser(id) { return db.find(id); } // Silently returns undefined. Good luck. TS — caught immediately: function getUser(id: string): User | null { return db.find(id); } // Handle null. Now. ────────────────────────────────── That function existed for months in production. TS didn't write the bug — but it made us face it on day one of migration. Mistakes I see every week: → Using `any` everywhere — you just turned off TypeScript → Casting with `as` to silence errors instead of fixing the type → No return types — so the compiler can't catch what you promised vs what you shipped → Treating TS as "JS with syntax" and skipping strict mode entirely What actually helps: → Turn on strict: true from day one — not after migration → Type your boundaries: API responses, function params, return values → Read the errors. TS is telling you something, not punishing you → Use `unknown` instead of `any` when you're unsure — it forces you to handle it ────────────────────────────────── TypeScript is a mirror, not a magic wand. The teams that get the most out of it are the ones who stop fighting the errors — and start listening to them. Be honest: when you migrated to TS, how many skeletons did it drag out of your closet? #TypeScript #JavaScript #WebDevelopment #SoftwareEngineering #CleanCode #FrontendDevelopment #NodeJS #DevLife #ProgrammingTips #CodeQuality
To view or add a comment, sign in
-
-
TypeScript strict mode isn't about catching bugs. It's about making your team speak the same language. Without strict mode, TypeScript fills in the blanks for you. A variable without a type? It's "any" A function parameter without annotation? Also "any" The code compiles. Everything looks fine. Until someone else reads your code and has to guess what a function accepts, what it returns, and whether null is a valid input. Without strict, every developer writes their own dialect. The types technically exist but they don't communicate anything. With strict, the type system becomes a shared contract. If a function accepts a string, it accepts a string. Not string-or-null-or-undefined-or-whatever. I work on a fintech codebase with strict mode on. When I read a function signature, I know exactly what it expects. No guessing. No tracing through three files to confirm. The types do the communication that comments used to do. There's another angle now: 94% of LLM-generated compilation errors are type-check failures. Strict TypeScript isn't just team communication anymore. It's a verification layer for AI-generated code. The stricter your types, the more low-signal mistakes get rejected before review ever starts. #JavaScript #TypeScript #WebDevelopment #SoftwareArchitecture #Frontend
To view or add a comment, sign in
-
I spent months treating TypeScript like "JavaScript with autocomplete." These 7 tips are what changed that. Swipe through if you've ever written any just to stop the red squiggles. 👇 What's in the carousel: → unknown over any — and why it matters → Discriminated unions for bulletproof state modeling → The satisfies operator (hidden gem) → ReturnType<>, Awaited<>, infer — stop rewriting types you already have → as const + template literal types for zero-cost type safety → 5 tsconfig wins you can add today If you're working with React, Next.js, or Node — these apply directly to your day-to-day code. Save this for the next time you reach for any. 🔖
To view or add a comment, sign in
-
You know how the TypeScript Type System works? A Big Picture of Type System..... A Static, Structural, compile-time type system. A Static Typescript check the code before running the code. function add(a:number, b:number){ return a + b } const result = add(10, "10") // Here will get an error We use the number type in b, but we passed 10 in quotation marks, which means a string. JavaScript Check = Runtime Typescript Check = Compile Time Type Inference let name = "Josim" // inferred as string let age = 10 // inferred as number //Typescript guesses the type automatically. Now you can say: Typescript guessed automatically - also Javascript Guess dynamically - Why use Typescript? let name = "josim" name = 10 //Javascript replace the name with 10, but typescript throw the error. Structural Type Checking TypeScript doesn’t care about names - it cares about shapes. type User={ name: string age: number } const user = { name: "Josim", age: 20, extra: true } function newUser(user:User){ return user } const result = newUser(user) console.log(result) // Worked //It matches the required structure DO NOT USE any const x // it means any let name:any = "Josim" any === Turning OF Typescript TypeScript builds a “virtual type model” of your code and checks if everything is consistent. Day 2.1 Let me comment on where I should improve my writing #typescript #reactjs #software_engineering #nextjs #mern_stack #best_developer #josim_hawladar
To view or add a comment, sign in
-
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