Have you ever been baffled by TypeScript's type narrowing, only to find out the problem isn't where you first look? 🤔 A couple of weeks ago, I was dealing with a subtle bug. The symptom was simple: a type error that would disappear under one condition but reappear under another without any obvious changes in logic. Here's a snippet that highlights the issue: ```typescript function processInput(input: string | number) { if (typeof input === 'string') { // Do something with the string } // More code that should only be applicable if input is a number console.log(input.toFixed(2)); } ``` In this scenario, TypeScript's type narrowing is expected to "forget" about `input` being a string after the `if` block. But, if additional complex structures or nested functions interact within the `if`, TypeScript can sometimes lose track, and you'll be stuck debugging an input type mismatch. The real headache? This problem rarely shows up in tests and is more likely to cause havoc when you upgrade TypeScript versions, since improvements can introduce new, stricter checks. To fix it, you can use an explicit type guard: ```typescript function isNumber(input: unknown): input is number { return typeof input === 'number'; } function processInput(input: string | number) { if (isNumber(input)) { // Guaranteed to be a number here console.log(input.toFixed(2)); } } ``` Always handle type assertions carefully, and regularly review your TypeScript configuration when upgrading. Have you come across similar issues? Share your experiences below! #TypeScript #JavaScript #CodeDebugging #WebDevelopment #SoftwareEngineering #TypeScript #JavaScript #CodeDebugging #WebDevelopment #SoftwareEngineering
TypeScript Type Narrowing Gotchas and Solutions
More Relevant Posts
-
🚀 Understanding Functions in TypeScript – With Real Examples 1.Basic Function : Explicit parameter and return types function add(a: number, b: number): number { return a + b; } 2.Optional Parameter : ' ? 'makes the parameter optional function greet(name?: string): string { return name ? `Hello ${name}` : "Hello Guest"; } 3. Default Parameter : Uses default value if no argument is passed function greetUser(name: string = "Guest"): string { return `Hello ${name}`; } 4. Rest Parameter : Handles multiple arguments as an array function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); } 5. Anonymous Function : Function without a name, often stored in a variable const multiply = function (a: number, b: number): number { return a * b; }; 6.Function Type : Defines how a function should look let calculate: (a: number, b: number) => number; calculate = (x, y) => x + y; 7. Void Function : Used when function does not return anything function logMessage(message: string): void { console.log(message); } 8. Never Function : Function that never completes execution function throwError(message: string): never { throw new Error(message); } ✨ Using TypeScript function patterns in React makes components more predictable, type-safe, and easier to scale as your application grows. 👍 Like | 💬 Comment | 🔁 Share #TypeScript #ReactJS #FrontendDevelopment #JavaScript #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Just open-sourced my daily driver for clean JS/TS error handling In JavaScript, error handling often ends up fragmented: ❌ try/catch blocks everywhere ❌ Manual response.ok checks ❌ JSON parsing that can throw at runtime try-fetch-catch brings Go-style error handling to JS/TS by replacing thrown exceptions with predictable tuples. ✨ What it gives you: 🌐 tryFetch — a drop-in fetch replacement that returns [error, data, response] 🛠️ tryCatch — wraps any sync or async function and returns [error, result] 🚫 No thrown exceptions ➡️ Linear, readable control flow 📦 Native ESM + CommonJS builds 🪶 Zero dependencies Example: const [err, user] = await tryFetch("/api/users/123"); if (err) // handle renderUser(user); // user is safe to consume If you care about predictable control flow, typed errors, and less boilerplate, this might be useful. 📦 npm: 🔗 https://lnkd.in/eqBESSWC 💬 Feedback welcome — especially from folks who’ve wrestled with fetch error handling before. #opensource #javascript #typescript #webdev #nodejs
To view or add a comment, sign in
-
Why for loop with setTimeout in JavaScript does not work the way we think Look at the simple code below: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } We can assume here that the output will be: 0, 1, 2 But the actual output is: 3, 3, 3 If the code is without setTimeout: for (var i = 0; i < 3; i++) { console.log(i); } The result is clear: 0, 1, 2 And the same result for the below as well: for (let i = 0; i < 3; i++) { console.log(i); } Output: 0, 1, 2 Confused!! Earlier, I bypassed the concept and simply used let instead of var whenever I used any asynchronous callback inside a for loop, so the code worked fine. But at the same time, I wanted the reason for the different behavior. Let me share what I explored after a long time going deeper into JavaScript and how it plays with variable types - var and let where loop is concerned. In case of let, JavaScript creates a variable instance in memory for each loop iteration. Each setTimeout looks for its corresponding instance: Iteration 0 → i0 (instance) → value: 0 → captured by setTimeout 1 Iteration 1 → i1 (instance) → value: 1 → captured by setTimeout 2 Iteration 2 → i2 (instance) → value: 2 → captured by setTimeout 3 But in case of var, there will be only a single instance, which is updated on each iteration. Since setTimeout takes 100 ms to execute, by that time the loop is finished, so the setTimeout always sees the final result. hashtag #javascript #webdevelopment #frontend #reactjs #nextjs #axios #fetchapi #JavaScriptTraps #FrontendDevelopment #AsyncJavaScript #Closures #JavaScriptTips #JavaScriptGotchas #CodingConcepts #programmingtips #developercommunity #codinglife #softwareengineering #webdev #learnjavascript #techcontent #100daysofcode
To view or add a comment, sign in
-
-
👉 Event Loop in Node.js JavaScript is single threaded, but Node.js can handle many tasks at the same time. This is possible because of the Event Loop. 👉 What Event Loop does -Continuously checks if the call stack is empty -Picks the next task from queues -Executes it without blocking the main thread 👉 How it works -Synchronous code runs in the call stack -Async tasks like timers, file system, and APIs go to background Once the stack is empty, Event Loop pushes tasks back to execution 👉 Execution order -Microtask queue → Promises, process.nextTick -Timers queue → setTimeout, setInterval -I O queue → file system, network calls -Check queue → setImmediate 👉 Why it matters -Handles thousands of requests efficiently -Keeps the application fast and non blocking 👉 Key point Node.js is single threaded, but highly concurrent because of the Event Loop. #nodejs #javascript #eventloop #backenddevelopment #webDevelopment
To view or add a comment, sign in
-
𝗥𝘂𝗻𝘁𝗶𝗺𝗲 𝗲𝗿𝗿𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗰𝗮𝗻 𝗵𝗮𝗹𝘁 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁 𝗮𝗻𝗱 𝗳𝗿𝘂𝘀𝘁𝗿𝗮𝘁𝗲 𝘂𝘀𝗲𝗿𝘀. 🛑 The absence of static typing in JavaScript often leads to unexpected issues that surface only when the code is executed. Debugging these errors can be time-consuming and challenging, especially in large codebases. This can ultimately delay project timelines and increase maintenance costs. TypeScript offers a robust solution by adding static typing to JavaScript. This enables developers to catch errors during development rather than at runtime, improving code quality and reducing debugging efforts. 💻 In my experience, adopting TypeScript leads to more predictable and maintainable code. ✅ Have you found that TypeScript improves code quality and reduces debugging efforts? #TypeScript #JavaScript #StaticTyping #BugPrevention #SoftwareDevelopment
To view or add a comment, sign in
-
🚨 𝐇𝐨𝐰 𝐭𝐨 𝐅𝐢𝐱 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭 𝐢𝐬𝐨𝐥𝐚𝐭𝐞𝐝𝐌𝐨𝐝𝐮𝐥𝐞𝐬 𝐄𝐫𝐫𝐨𝐫 𝐢𝐧 𝐍𝐞𝐱𝐭.𝐣𝐬? If your Next.js build fails with this message: Re-exporting a type when isolatedModules is enabled requires using export type Don’t worry, it’s not a complex bug. It’s just about being clear with TypeScript. 𝐖𝐡𝐚𝐭’𝐬 𝐀𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐇𝐚𝐩𝐩𝐞𝐧𝐢𝐧𝐠? When `isolatedModules` is enabled, each file is compiled independently. So TypeScript must know exactly: - what is real JavaScript code that needed at runtime. - what is only for type checking. If you export a type like a normal value, the compiler expects it to exist in JavaScript but it doesn’t. That’s why the build fails. ❌ 𝐖𝐫𝐨𝐧𝐠 𝐖𝐚𝐲 export { Profile, saveProfile } from './helpers'; If `Profile` is a type and `saveProfile` is a function, this causes errors in isolated builds. ✅ 𝐂𝐨𝐫𝐫𝐞𝐜𝐭 𝐖𝐚𝐲 // runtime exports export { saveProfile } from './helpers'; // type-only exports export type { Profile } from './helpers'; Easy Rule to Remember: - Use `export {}` for functions, components, constants - Use `export type {}` for types and interfaces Have you encountered this issue? 😀 #creowis #TypeScript #NextJS #FrontendDev #EngineeringTips #WebDevelopment
To view or add a comment, sign in
-
-
TypeScript didn’t make JavaScript complex. It made the complexity visible. For years we blamed JavaScript for: - runtime errors - broken refactors - “it worked yesterday” bugs TypeScript didn’t add these problems. It just stopped letting us ignore them. Types are not about being “strict”. They’re about intent. - What does this function expect? - What does it return? - What can be null — and what can’t? - What breaks if I change this? That’s not overhead. That’s documentation that doesn’t lie. Yes, TypeScript can feel annoying at first. Yes, it slows you down… for about two weeks. Then something interesting happens: - refactors get safer - code reviews get easier - onboarding gets faster - production gets quieter The biggest TypeScript benefit isn’t fewer bugs. It’s confidence. Confidence to change code. Confidence to delete code. Confidence to scale a codebase without fear. TypeScript isn’t about types. It’s about engineering discipline. If you’ve worked with both JS and TS at scale, you already know. What was the moment TypeScript “clicked” for you? #typescript #javascript #frontend #softwareengineering #cleanCode #webdevelopment #engineeringCulture #devLife
To view or add a comment, sign in
-
👨💻 TypeScript Review Question: Function Length. I worked on a question that asked me to implement a function called functionLength that returns the number of parameters a function expects. This question is very straightforward once you understand what the .length data property does. In JavaScript, every function has a built-in .length property. ✍️ This question serves as a helpful prerequisite for currying problems. In currying problems, you often need to know how many arguments a function expects before deciding to execute it or keep returning partial functions. 🧠 #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #TypeScript
To view or add a comment, sign in
-
-
What Is the JavaScript Event Loop? The Event Loop is the core mechanism that enables JavaScript to handle asynchronous operations—such as setTimeout, Promises, and API calls—despite being a single-threaded language. While JavaScript can execute only one task at a time, the Event Loop efficiently manages execution order by deciding what runs next and when. Key Components of the Event Loop 🔹 Call Stack Executes synchronous JavaScript code Follows the LIFO (Last In, First Out) principle 🔹 Web APIs Provided by the browser environment Handles asynchronous tasks like setTimeout, fetch, and DOM events Executes outside the JavaScript engine 🔹 Callback Queue (Macrotask Queue) Stores callbacks from setTimeout, setInterval, and DOM events Tasks wait here until the Call Stack is free 🔹 Microtask Queue Contains Promise.then, catch, and finally callbacks Always executed before the Callback Queue 🔹 Event Loop Continuously monitors the Call Stack When the stack is empty: Executes all Microtasks first Then processes tasks from the Callback Queue ✅ Why It Matters Understanding the Event Loop is essential for writing efficient, non-blocking JavaScript, debugging async behavior, and building high-performance applications—especially in frameworks like React and Node.js. #JavaScript #EventLoop #WebDevelopment #Frontend #AsyncProgramming #ReactJS
To view or add a comment, sign in
-
-
A lot of developers ask me what they need to do to become experts when it comes to Javascript or Typescript. Usually, my answer is you need to know the right tools that you should use for the job. For instance, we have three kinds of 'for' loops in Javascript. You can of course use the 'for' loop for even those things that can be done by the other two 'for' loops but easily and with less verbosity. However, can you do better? The answer is of course. Use the 'for-of' loop if you iterating through arrays or strings, or utilize the 'for-in' loop for objects which will lead to much cleaner and maintainable code. Similarly, you can apply this to other things. Follow for more such content. 🔔
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