When you first come across 'Conditional Types' in TypeScript, there’s one keyword that suddenly starts appearing everywhere - 'infer'. And when people first see it, the reaction is usually - 'Wait… TypeScript can extract types now?' Yes. And that’s exactly what infer is about. In simple terms, 'infer' allows TypeScript to capture a type from inside another type and give it a name, so you can reuse it. It only works inside conditional types, and that’s important. Using this keyword, you are asking TypeScript - 'If this type matches a certain shape, can you pull out a part of it for me?' This is really powerful because in real code, we often work with wrapped types. Promises wrap values, Arrays wrap elements. Functions wrap return types, APIs wrap responses etc. And without 'infer', you’d have to manually describe every possible variation. With 'infer', you can extract the interesting part automatically. This is the reason TypeScript can unwrap Promise values, extract function return types, pull parameter types from functions, and power utility types like 'ReturnType', 'Awaited', and 'Parameters'. All of those are built on 'infer'. Another important thing to understand is that 'infer' doesn’t 'guess'. It only works when the surrounding conditional type matches. If the structure doesn’t match, the conditional type falls back to its alternative branch. Remember - 1. Conditional types decide which branch to take. 2. 'infer' lets you name a piece of the type inside that branch. #TypeScript #JavaScript #Programming #WebDevelopment #Coding
TypeScript's 'infer' Keyword: Extracting Types from Wrapped Values
More Relevant Posts
-
Most TypeScript devs write types that describe shape. 'Branded Types' let you write types that enforce intent. In my last post, we saw how TypeScript's structural type system can let logic errors slip through unnoticed. Same shape = same type, even when they mean completely different things. So how do we fix that? Enter 'Branded Types.' The idea is simple: take any base type and attach an invisible "brand" to it, a unique marker that exists purely at the type-level. Two types might look structurally identical, but if they carry different brands, TypeScript treats them as incompatible. Think of it like a stamp on a document. The paper looks the same. The content might look the same. But without the right stamp, it's not valid. The best part? This costs you nothing at runtime. Branded types are a compile-time construct only. No extra objects, no performance overhead. Just stronger guarantees from your type-checker. This pattern shines in situations where plain primitives aren't expressive enough. Passwords vs plain strings. User IDs vs order IDs. Verified emails vs unverified ones. Anywhere you want TypeScript to stop treating two things as interchangeable just because they share a shape. It's one of those techniques that feels like a workaround at first, but once it clicks, you start seeing exactly where it belongs in your codebase. #TypeScript #Programming #Coding #WebDevelopment #JavaScript
To view or add a comment, sign in
-
-
If you've been following along with JavaScript for a while, you've probably used classes. But TypeScript takes class-based development to another level with full type safety and better tooling support. My latest post breaks down TypeScript classes from first principles: 🏗️ Properties and Methods - How TypeScript adds static typing to your class members ⚙️ Constructors - Parameter properties that cut your boilerplate in half 🔍 Instances and Type Safety - Catching errors before they reach production 📐 Real-World Patterns - From user management to shopping carts with type-safe methods The jump from JavaScript classes to TypeScript classes is smaller than you think, but the benefits are massive. Better autocomplete, instant error detection, and refactoring confidence. Whether you're building APIs, frontend components, or data models, understanding TypeScript classes is fundamental to writing maintainable code. Read the full guide: https://lnkd.in/gf43JCeb #TypeScript #WebDevelopment #JavaScript #Programming #SoftwareEngineering #OOP #TypeSafety
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗴𝗿𝗲𝗮𝘁, 𝗯𝘂𝘁 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗮 𝗴𝗮𝗺𝗲-𝗰𝗵𝗮𝗻𝗴𝗲𝗿. 🚀 One of the biggest headaches in plain JS is passing the wrong type of argument to a function and only finding out at runtime. TypeScript solves this by letting us define strict contracts for our code. By simply adding types to your parameters and explicitly stating your return type, you get two massive benefits: 1️⃣ Instant IDE autocomplete 2️⃣ Catching bugs before you even hit save // The TypeScript Way 🛡️ function calculateDiscount(price: number, discount: number = 10): number { return price - (price * (discount / 100)); } // Hovering over this, your IDE knows exactly what to expect! const finalPrice = calculateDiscount(500); Once you start strictly typing your functions, you never want to go back. I’ve just uploaded a new video diving deep into everything you need to know about functions in TypeScript. It’s the latest episode in my ongoing TypeScript series on YouTube, where we're breaking down these concepts step by step. 𝗖𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗳𝘂𝗹𝗹 𝘁𝘂𝘁𝗼𝗿𝗶𝗮𝗹 𝗵𝗲𝗿𝗲: https://lnkd.in/gyexUVgs What’s your favourite TS feature that saves you the most time during debugging? Let me know in the comments! #TypeScript #JavaScript #WebDevelopment #SoftwareEngineering #CodingTutorial #DeveloperCommunity
To view or add a comment, sign in
-
-
🚀 30 Days — 30 Coding Mistakes Beginners Make Day 13/30 I copied an object… and the original data changed 😐 const newUser = user Then I updated newUser… and user also changed. Because objects in JavaScript are stored by reference, not value. Both variables pointed to the same memory. Fix 👇 const newUser = { ...user } Now a new object is created. This concept is very important in React state updates and debugging strange UI behavior. Day 14 tomorrow 👀 #30DaysOfCode #javascript #reactjs #frontend #webdevelopment #codeinuse
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
-
-
Still Using JavaScript in React? Here's What You're Missing I used to think TypeScript was just "extra work"-until I spent 3 hours debugging a runtime error that would've been caught in 3 seconds with static typing. This slide perfectly captures the shift: ❌ Without TypeScript: • Mystery bugs appearing in production • Refactoring feels like defusing a bomb • "What type is this prop again?" *checks 5 files* ✅ With TypeScript: • Errors caught before you hit save • Confidence to refactor entire codebases • IntelliSense that actually reads your mind The messy scribble vs. clean structure isn't just aesthetic—it's the mental load difference between guessing and *knowing*. Sure, there's a learning curve. But the time you "lose" writing types? You 10x it back in debugging hours saved and team onboarding speed. The best part? You don't need to migrate everything. Start with strict mode on new files, let the compiler teach you. React devs-what's your take? TS all the way, or still team JS? #TypeScript #ReactJS #JavaScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #CleanCode #DeveloperExperience #CodeQuality #TechLeadership #ProgrammingTips #LearnToCode #FullStackDevelopment #ModernWebDev #DevCommunity
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟑/10 – 𝐈𝐧-𝐛𝐮𝐢𝐥𝐭 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 & 𝐀𝐫𝐫𝐚𝐲 𝐎𝐩𝐞𝐫𝐚𝐭𝐢𝐨𝐧𝐬 🔍📃 ✨ Today I explored some of the most useful in-built functions in TypeScript (via JavaScript) that make problem-solving easier: 🔹 split (""): This method takes a string and breaks it into an array of its individual characters. It’s useful when you want to manipulate or process each character separately. 🔹 reverse (): This method reverses the order of elements in an array. When applied after splitting a string, it flips the sequence of characters. 🔹 join (""): This method takes all elements of an array and combines them back into a single string. By using an empty string as the separator, the characters are joined without spaces. Examples - 1. Palindrome 2. Reverse of a string 3. Max of an array #TypeScript#Programming #Learning#Automation#Playwright
To view or add a comment, sign in
-
-
There’s one very important gotcha with Conditional Types in TypeScript that catches almost everyone at some point. It’s called 'Distributivity.' At first, conditional types feel predictable. You write a condition. TypeScript checks it. You get a result. But when union types enter the picture, things suddenly behave very differently. The core idea that you need to understand is - Conditional types distribute over union types, but only in very specific situations. So, what does 'distribute' actually mean? When a conditional type is written using a generic type parameter, and that parameter is later given a union, TypeScript doesn’t check the union as a whole. Instead, it applies the condition to each member of the union individually, and then unions the results back together. This behavior is extremely powerful, but also very easy to misunderstand if you don’t know it exists. Now here’s the subtle part that causes confusion. Distributivity only happens when the conditional type is applied to a generic type parameter. If you write a conditional type directly against a union type, TypeScript does not distribute. In that case, TypeScript checks the union as a single unit. And if any member of that union fails the condition, the entire check fails. That’s why two conditional types that look almost identical can produce completely different results. One distributes. The other doesn’t. This distinction explains a lot of "why did this become 'never'?" moments when working with conditional types. There’s also an important escape hatch. If you don’t want distributive behavior, you can explicitly turn it off by wrapping the type in a tuple. This tells TypeScript: 'Treat this as one thing, not a union of things.' And interestingly, you can also force distribution in situations where you’re not using a type parameter, by introducing one via 'infer.' At that point, TypeScript is back in a generic context, and distributivity kicks in again. The key takeaway is that Conditional types don’t behave differently by accident. They behave differently based on how you write them. Once you understand when distributivity applies, and when it doesn’t, a lot of confusing behavior suddenly becomes predictable. #TypeScript #JavaScript #Programming #Coding #WebDevelopment
To view or add a comment, sign in
-
-
Good JavaScript code isn’t about fancy syntax. It’s about clarity, maintainability, and smart decisions. A few habits that can instantly improve your JS code 👇 ✔ Use meaningful variable names ✔ Keep functions small and focused ✔ Comment why, not what ✔ Avoid callback hell — use async/await ✔ Write code for humans, not just machines Small improvements in JavaScript lead to cleaner code and fewer bugs over time. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #CleanCode #Programming #SoftwareEngineering #DeveloperLife #CodeQuality
To view or add a comment, sign in
-
-
🚀 30 Days — 30 Coding Mistakes Beginners Make Day 16/30 My component received a new userId… but UI still showed the old user 😐 The reason? I wrote: useEffect(() => { fetchUser(userId) }, []) Empty dependency array means: run only once on mount. So when userId changed, React never fetched new data. Fix 👇 useEffect(() => { fetchUser(userId) }, [userId]) Dependencies tell React WHEN to re-run the effect. Missing dependency = stale UI data. Day 17 tomorrow 👀 #30DaysOfCode #reactjs #javascript #frontend #webdevelopment #codeinuse
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