'Pick' and 'Omit' are great for objects. But what about union types? If you’ve used 'Pick' and 'Omit' before, you already understand one important idea in TypeScript - 'We can derive new types from existing ones instead of rewriting them.' But 'Pick' and 'Omit' only work on object shapes. What happens when you’re working with union types instead? That’s exactly where 'Extract' and 'Exclude' come in. Think of them as filters for union types. While 'Pick' and 'Omit' operate on keys of objects, 'Extract' and 'Exclude' operate on members of union types. Conceptually, 'Extract' keeps what matches & 'Exclude' removes what matches. So, when you write 'Extract<A, B>', it means 'From union A, keep only the members that are assignable to B.' Similarly, when you write 'Exclude<A,B>', it means 'From union A, remove anything that is assignable to B.' These utility types shine when your codebase grows. They help you avoid duplicating unions, and keep types in sync automatically. If the original union evolves, your derived types evolve with it. No manual updates needed. #TypeScript #JavaScript #WebDevelopment #Programming #SoftwareEngineering
TypeScript Union Types: Extract & Exclude
More Relevant Posts
-
Hii Folks 🙂 Yesterday, while discussing the JavaScript Event Loop with a senior, I realized something important. Most of us explain the Event Loop using queues and the call stack. That explanation is correct, but it’s incomplete. It answers how things run, not why they behave the way they do. The deeper question came up: Before the Event Loop even starts scheduling tasks, how does JavaScript know what those tasks are allowed to access? That’s where concepts like the compiler and lexical scope quietly enter the picture. JavaScript first reads the code and builds an understanding of it. Variable scope, function boundaries, and memory references are decided before execution begins. This is not the Event Loop’s responsibility. The Event Loop only works with what already exists. Lexical scope determines which variables belong to which functions. Closures decide what stays in memory even after a function finishes. None of this is created by the Event Loop, but all of it affects how async code behaves later. Data structures play a similar hidden role. The call stack is just a stack. Task queues are just queues. The scope chain behaves like a linked structure. The Event Loop doesn’t interpret logic. It simply moves execution between these structures based on a few strict rules. That discussion made one thing clear to me: If we don’t understand compiler behavior, lexical scoping, and basic data structures, the Event Loop will always feel confusing or “magical”. Async issues are rarely caused by the Event Loop itself. They usually come from misunderstanding scope, memory, or execution order. Once you see the Event Loop as a coordinator rather than a decision-maker, a lot of confusion disappears. #JavaScript #EventLoop #LexicalScope #Closures #AsyncProgramming #WebDevelopment #FrontendDevelopment #BackendDevelopment #FullStackDeveloper #SoftwareEngineering #ComputerScience #ProgrammingConcepts #DataStructures #DeveloperLearning #LearningInPublic #TechDiscussions #DeveloperCommunity #CodingLife #Debugging #EngineeringMindset #TechCareers
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 — 𝗖𝗼𝗺𝗽𝗹𝗲𝘁𝗲 𝗡𝗼𝘁𝗲𝘀 𝗳𝗼𝗿 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 Closures are one of the most powerful and important concepts in JavaScript. They allow a function to access variables from its outer scope even after the outer function has finished executing. Understanding closures helps you master data privacy, function factories, callbacks, and advanced patterns used in modern frameworks like React. These notes break down closures in a simple and practical way with clear explanations and real-world use cases to strengthen your core JavaScript knowledge. #JavaScript #Closures #JSConcepts #WebDevelopment #FrontendDevelopment #LearnJavaScript #Programming #DeveloperNotes #Coding #SoftwareEngineering
To view or add a comment, sign in
-
“Clean code” is often equated with “short code.” But in a complex context, the priority should be predictability. I recently saw a bug caused by a seemingly harmless refactor. A developer swapped a standard loop for .forEach(), not realizing that a return statement inside a callback behaves fundamentally differently than a return in a block scope. It’s a classic trap: 1️⃣ return in .forEach acts like continue. 2️⃣ It doesn't support break. 3️⃣ It’s a minefield for async/await logic. While declarative patterns are elegant, they can sometimes hide the true intent of the code and increase the cognitive load for the next person reading it. #JavaScript #SoftwareEngineering #CleanCode #WebDevelopment #ProgrammingTips #TechLeadership
To view or add a comment, sign in
-
🧠 How JavaScript Works Inside the V8 Engine Many developers use JavaScript daily, but few understand the magic behind its speed and flexibility. Let's break down what really happens when your JS code runs inside the V8 engine. Here’s the execution pipeline step by step: 1. Parsing 🏗️ V8 takes your source code and builds an Abstract Syntax Tree (AST) a structured representation of your code's logic. ( https://astexplorer.net/ ) 2. Ignition Interpreter 🔥 V8’s Ignition interpreter converts AST into Bytecode and starts executing immediately. This gives JavaScript its famous fast startup. 3. TurboFan Compiler 🏎️ While running, V8 monitors for "Hot Code" frequently used functions. TurboFan kicks in, compiling this hot code into Optimized Machine Code for peak performance. 4. De-optimization ⚠️ If assumptions break (e.g., a number suddenly becomes a string), V8 smartly de-optimizes and falls back to the interpreter to keep execution stable. 5. Garbage Collection 🧹 V8’s Orinoco Garbage Collector automatically cleans unused memory, preventing leaks and keeping apps responsive. Why does this matter? V8’s hybrid approach interpreter + compiler delivers both quick startup and sustained high performance. It’s the reason modern JS can power everything from web apps to server-side runtimes like Node.js. 🔁 Key Takeaway: JavaScript isn’t just interpreted or just compiled. It’s both—thanks to V8’s intelligent, multi-tiered execution pipeline. #JavaScript #V8Engine #WebDevelopment #Programming #SoftwareEngineering #Tech #NodeJS #Performance #Coding #Developer
To view or add a comment, sign in
-
-
🧠 The bug that cost me 3 hours… and taught me (again) how TypeScript lies to you Today I spent almost 3 hours debugging something that made absolutely no sense. Same DTO. Same ValidationPipe. Same endpoint structure. ✅ Works perfectly in one place. ❌ Completely breaks in another. The logs were weird: DTO looked like a function JSON.stringify() returned undefined ValidationPipe kept throwing BadRequestException request body existed, but DTO fields were undefined Everything looked correct. So naturally: checked pipes checked middleware checked request payload blamed NestJS blamed class-validator questioned life decisions The confusing part? The exact same logic worked elsewhere in the project. After digging through pipes, decorators, and request lifecycle… the problem turned out to be one single word: import type { UpdateUserByAdminDTO } from "../dto/admin-user.dto"; Yep. import type. TypeScript removes type-only imports at runtime. But NestJS needs DTO classes at runtime for validation, transformation, and metadata reflection. So ValidationPipe wasn’t receiving a class — it was receiving… nothing useful. Changing it to: import { UpdateUserByAdminDTO } from "../dto/admin-user.dto"; Fixed everything instantly. Lesson (that I apparently need to relearn every few months): If a class is used by: decorators ValidationPipe Swagger helpers (PartialType, OmitType) class-validator class-transformer 👉 it is NOT a type. It’s runtime code. And import type will silently break it. Sometimes the hardest bugs are not complex ones. They’re the ones where everything looks correct. And the fix is one deleted word. #TypeScript #NestJS #BackendDevelopment #SoftwareEngineering #Debugging #WebDevelopment #ProgrammingLife #Developers #LessonsLearned #Coding
To view or add a comment, sign in
-
-
🚀 Day 5(JavaScript): Mastering Array Transformations Today’s challenge was a deep dive into Functional Programming in JavaScript. The goal: manually implement a transformation utility without relying on the built-in .map() method. Key Insights: Immutability: Learning to transform data while keeping the original array intact—a core principle for predictable state management. High-Order Functions: Strengthening my understanding of how callbacks interact with data and their indices ($i$) under the hood. Efficiency: Focusing on manual iteration to appreciate the logic that powers modern JavaScript frameworks. Rebuilding these "standard" methods from scratch is a great reminder that understanding the fundamentals is what makes for better debugging and cleaner architecture. Onward to Day 6! ⚡️ #JavaScript #SoftwareEngineering #CodingChallenge #WebDevelopment #LeetCode
To view or add a comment, sign in
-
-
Think JavaScript just reads your code line-by-line? Think again. 🧠 We often hear that JavaScript is a single-threaded interpreted language. It reads code, executes a task, and moves on. Simple, right? But actually, a lot happens before that execution phase kicks in. The JS Engine (like V8) doesn't just look at var a = 10; and run it. It has to understand it first. Here is the 3-step compilation pipeline that happens behind the scenes: 1️⃣ Tokenization (Lexing): The engine breaks code into small "tokens" (keywords, variables, operators). 2️⃣ Parsing: It arranges these tokens into a tree structure called an AST (Abstract Syntax Tree). 3️⃣ Code Generation: Finally, it converts that AST into executable machine code. Only then does your code actually run. It’s fascinating how much engineering goes into processing even a single line of JavaScript! Have you looked into the V8 engine architecture lately? It’s a rabbit hole worth going down. 👇 #JavaScript #WebDevelopment #Frontend #Engineering #TechTips
To view or add a comment, sign in
-
TypeScript has this weird reputation. New developers see it and think, 'Oh, it's just JavaScript with type annotations so the compiler catches bugs.' That's not wrong, but it's also not the full picture. The real power? Type composition and inference. Once you start thinking about types as sets of values instead of just annotations, everything clicks. Intersections, unions, narrowing, discriminated types—these aren't just syntax tricks. They're tools that let you express complex relationships in your code that the compiler actually understands. We've helped teams shift from defensive coding (throwing assertions everywhere) to leveraging TypeScript's type system to prevent entire categories of bugs at compile time. It's a mindset change, not just a syntax change. If you're still reaching for 'as SomeType' assertions regularly, you might be fighting the language instead of working with it. What's one TypeScript pattern that fundamentally changed how you write code?
To view or add a comment, sign in
-
Type vs Interface in TypeScript — Know the Difference Both type and interface help define the shape of data, but they’re not the same. =>Interface Best for defining object structures Supports declaration merging Ideal for public APIs and class contracts =>Type More flexible (unions, intersections, primitives) Can combine multiple types Great for complex type logic =>Rule of thumb Use interface for object-oriented design and extensibility. Use type when you need flexibility or advanced compositions. Understanding this distinction helps you write cleaner, scalable, and maintainable TypeScript code #TypeScript #JavaScript #WebDevelopment #Frontend #FullStack #Learning #Programming #Tech
To view or add a comment, sign in
-
-
𝐈𝐟 𝐲𝐨𝐮𝐫 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭 𝐠𝐞𝐧𝐞𝐫𝐢𝐜𝐬 𝐟𝐞𝐞𝐥 𝐥𝐢𝐤𝐞 𝐠𝐥𝐨𝐫𝐢𝐟𝐢𝐞𝐝 𝐚𝐧𝐲𝐬, 𝐲𝐨𝐮'𝐫𝐞 𝐦𝐢𝐬𝐬𝐢𝐧𝐠 𝐚 𝐭𝐫𝐢𝐜𝐤. Writing reusable functions with generics is powerful, but leaving your type parameters too broad can defeat the purpose of TypeScript. How often do you find yourself writing obj[key as any] or obj[key as keyof T] to appease the compiler, feeling like you've lost type safety? The fix is often simple: constrain your generic type parameter to enforce type safety at compile time. Instead of: ```typescript function getPropertyBad<T>(obj: T, key: string) { return obj[key as keyof T]; // 'as keyof T' is an assertion, not a guarantee } ``` Do this: ```typescript function getPropertyGood<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; // Type-safe! K is guaranteed to be a key of T } interface Product { id: string; name: string; price: number; } const product: Product = { id: 'p1', name: 'Widget', price: 29.99 }; const productName = getPropertyGood(product, 'name'); // productName is string const productPrice = getPropertyGood(product, 'price'); // productPrice is number // getPropertyGood(product, 'description'); // Argument of type '"description"' is not assignable to parameter of type '"id" | "name" | "price"'. // The compiler catches typos or non-existent keys immediately! ``` This pattern is a game-changer for building robust utility functions, custom React hooks, or any helper that needs to access object properties dynamically without sacrificing type safety. You get auto-completion and compile-time error checking, making your code much more maintainable and refactor-friendly. Are there specific generic constraints you find yourself using repeatedly in your projects? #TypeScript #FrontendDevelopment #React #WebDevelopment #SoftwareEngineering
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