In my last article, I talked about the 'Parameters<T>' utility type in TypeScript which is used to get the types of the parameters of a function. After extracting function parameters using Parameters<T>, the next logical question is - "What if we want to extract the return type of a function?" That’s exactly what 'ReturnType<T>' helps us do. 'ReturnType<T>' takes a function type and gives us the type of the value it returns. This is incredibly useful when you’re reusing the result of a function elsewhere or you’re wrapping or composing functions, or maybe you want to avoid manually updating types if the function’s return type changes. Just like 'Parameters<T>,' it pairs perfectly with 'typeof.' You can pass an existing function directly, and TypeScript will automatically infer the return type for you. But things get interesting when async functions enter the picture. An 'async' function will return a 'Promise,' which means 'ReturnType<typeof fn>' gives you something like 'Promise<X>' instead of just 'X'. To handle that, TypeScript has 'Awaited<T>,' a utility type that unwraps the resolved type from a Promise. So, if you combine both, you get the actual value type returned by an async function. In other words, 'Awaited<ReturnType<typeof fn>>' gives you the true resolved type. This combination becomes super useful when writing helpers or working with async workflows where you want full type safety. Together, 'ReturnType' and 'Awaited' give you a clean, readable, and type-safe way to infer what a function, synchronous or asynchronous, really returns. #TypeScript #Programming #WebDevelopment #Coding #JavaScript
How to extract return types of functions in TypeScript
More Relevant Posts
-
There’s a subtle behavior in TypeScript that surprises many developers. A variable can start with the type 'any,' but then its type can change (or 'evolve') as you assign values to it. This is called 'Evolving any.' This happens when you declare a variable without a type and without an initial value. When you do this, TypeScript doesn’t know what the variable should be. So it temporarily treats it as 'any.' But as soon as you assign a value, TypeScript refines the type based on that value, and it continues to update that type as you assign new values later. In other words, the type 'evolves' to match the values being assigned. This is different from explicitly setting the type as 'any'. When you explicitly set the type of a variable as 'any,' the variable always remains 'any.' TypeScript won't do any type checking on it, and you lose type safety completely. But when you declare a variable without a type and without an initial value, it starts as 'any,' but each assignment changes the inferred type. So, 'evolving any' still preserves type checking, while an explicit 'any' does not. Arrays evolve as well. If you start with an empty array, then TypeScript infers it as 'any[]' initially. But once you start adding values, the array type evolves accordingly. After pushing numbers, it becomes 'number[].' After later pushing a string, it becomes '(number | string)[].' TypeScript does this because it is designed to support gradual typing. Sometimes you genuinely don’t know the variable value at the moment of declaration, and 'evolving any' allows type inference to 'catch up' later. #TypeScript #JavaScript #Coding #Programming #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Day 4 Challenge: Deep Dive into JavaScript Event Loop & Async Programming:- Today, I explored some really tricky aspects of JavaScript that every developer should master to handle async code efficiently. Here’s a quick summary of what I learned: Topics Covered: Promises & Chaining Understanding .then(), .catch(), and .finally() How throwing errors affects the chain and how .catch() recovers the flow Microtask queue behavior and how returned values continue the chain Async/Await How await pauses execution and schedules continuation as a microtask or macrotask Difference between synchronous, microtask, and macrotask queues setTimeout vs Promises Macrotask vs Microtask queue How Promise.resolve().then(...) always runs before setTimeout(..., 0) Combining async/await with timers and promises Tricky Scenarios I Practiced Nested promises with return values and errors Async functions with multiple awaits and promises Event loop behavior with microtasks, macrotasks, and finally blocks Key Takeaways .then() callbacks are microtasks, always run after synchronous code. await pauses the function but doesn’t block the main thread. .catch() handles thrown errors and allows the chain to continue. .finally() always runs, but doesn’t alter the return unless explicitly returned. Microtasks run before any macrotasks like setTimeout. 💡 Example outputs I solved: Promises chaining with errors → understanding how .catch() and .finally() interact Async/Await + setTimeout + Promise.resolve() → mastering event loop order This practice really helped me visualize how JavaScript executes async code line by line, which is crucial for building robust and bug-free applications. #Hashtags #Day4Challenge #JavaScript #AsyncAwait #Promises #EventLoop #Microtasks #Macrotasks #WebDevelopment #FrontendDevelopment #CodeLearning #JavaScriptDeepDive #JSChallenges #CodingPractice #LearnJS #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Mastering TypeScript Basics (The Smart Way!) When I started learning TypeScript, a few concepts really helped me write cleaner and safer code. Here’s a quick breakdown 👇 🔹 Tuples – Fixed-length arrays with defined types. 🔹 Enums – Define a set of named constants. 🔹 Any – Turns off TypeScript type checking (use carefully!). 🔹 Unknown – Similar to any, but safer. You must check the type before using it. 🔹 Void – When a function doesn’t return anything. 🔹 Null / Undefined – Represent “nothing” or “not assigned yet.” 🔹 Never – Used for functions that never return (like infinite loops or errors). TypeScript might look strict at first, but once you understand these basics — it actually saves you from countless bugs 💪 #TypeScript #JavaScript #WebDevelopment #FrontendDevelopment #FullStackDevelopment #Programming #SoftwareDevelopment #CodeNewbie #LearnToCode #CodingJourney #DeveloperCommunity #100DaysOfCode #WebDev #TypeSafety #TechLearning #JS #DevLife #CleanCode #SoftwareEngineer #WebAppDevelopment #ModernJavaScript #CodingLife #Developer #TechJourney #TypeScriptTips #ProgrammingLife #TypeScriptDeveloper
To view or add a comment, sign in
-
-
🚀 JavaScript Scope Understanding scope is one of the keys to writing clean, bug-free JavaScript. 👉 Global Scope: Accessible everywhere 👉 Function Scope: Accessible only inside the function 👉 Block Scope (let, const): Accessible only inside {} 👉 Local Scope: Exists only where it's declared Mastering scope = fewer errors + cleaner code. 💡 Happy coding! ⚡ #JavaScript #JS #WebDevelopment #Frontend #Coding #Programmer #Developer #SoftwareEngineer #LearningToCode #TechLearning #100DaysOfCode #CodeNewbie #WebDeveloper #TechEducation #CleanCode #ProgrammingBasics #SoftwareDevelopment #ES6 #FullStack #TechCommunity #Debugging #WomenWhoCode #Developers #LearnJavaScript #NaveenCodes
To view or add a comment, sign in
-
🚀 Master TypeScript in 2025: From Zero to Hero! Just published a comprehensive TypeScript guide covering everything you need to know: ✅ Basic Types & Interfaces ✅ Generics & Advanced Types ✅ OOP with Classes ✅ Real-world Patterns ✅ TypeScript with React & Express ✅ Best Practices & Common Pitfalls Whether you're a beginner or looking to level up your TypeScript skills, this 4500+ word guide has you covered with practical examples and code snippets. Perfect for: 👨💻 JavaScript developers wanting to learn TypeScript 📈 Teams looking to improve code quality 🎯 Anyone building scalable applications Read the full guide here: https://lnkd.in/e5XgCxAH What's your biggest challenge with TypeScript? Drop a comment below! 👇 #TypeScript #WebDevelopment #JavaScript #Programming #SoftwareDevelopment #Coding #TechTutorial #LearnToCode
To view or add a comment, sign in
-
-
⚔️ TypeScript vs. JavaScript — The Strict Teacher vs. The Cool Friend! Both are essential in the frontend world — but they bring completely different vibes to your code. 📘 TypeScript: The Strict Teacher Type: Superset of JavaScript that adds static typing. Syntax: Structured and predictable — you declare what’s allowed. Error Handling: Catches errors before your code even runs. Scalability: Ideal for large codebases and teams. Best For: Enterprise projects that demand consistency, safety, and long-term maintainability. 🟨 JavaScript: The Cool Friend Type: Dynamic, interpreted language — runs everywhere. Syntax: Flexible and forgiving — minimal setup, quick to start. Error Handling: Runtime errors (you learn by breaking things 😅). Scalability: Great for small to mid-sized projects or rapid prototyping. Best For: Quick builds, experiments, and projects where speed matters more than structure. 🧠 The Easiest Analogy #TypeScript is a strict teacher 👩🏫 — demands discipline but makes you a stronger coder. #JavaScript is a cool friend 😎 — lets you explore freely but sometimes lets you fall. 💬 Which one do you prefer for your daily development — the structure of TypeScript or the freedom of JavaScript? #FrontendDevelopment #WebDevelopment #Coding #Programming #LearnToCode #SoftwareDevelopment #Frontend #TechLearning #CodeTips #DevCommunity
To view or add a comment, sign in
-
-
✨ Mastering JavaScript means understanding not just 𝘸𝘩𝘢𝘵 works - but 𝘸𝘩𝘺 it works. In our new blog post, “𝙁𝙧𝙤𝙢 𝙄𝙣𝙩𝙪𝙞𝙩𝙞𝙤𝙣 𝙩𝙤 𝙋𝙧𝙤𝙛𝙞𝙘𝙞𝙚𝙣𝙘𝙮: 𝙁𝙪𝙣𝙘𝙩𝙞𝙤𝙣 𝙏𝙧𝙖𝙣𝙨𝙛𝙤𝙧𝙢𝙖𝙩𝙞𝙤𝙣𝙨 𝙞𝙣 𝙅𝙖𝙫𝙖𝙎𝙘𝙧𝙞𝙥𝙩”, Anju Karanji unpacks that mindset beautifully. 💜🧠 If 𝗣𝗮𝗿𝘁 𝟮 was about chaining and composing functions, 𝗣𝗮𝗿𝘁 𝟯 dives into how functions themselves can evolve - transforming behavior, optimizing performance, and reshaping how we think about logic. ⚙️💭 Anju takes you on a journey from simple wrappers → to once-only execution patterns → to building your own memoization utility that makes code both elegant and efficient. 🧩✨ 🔍 𝗪𝗵𝗮𝘁 𝘆𝗼𝘂’𝗹𝗹 𝗹𝗲𝗮𝗿𝗻: 🎯 How higher-order functions reshape behavior 🧱 Building a once() wrapper from scratch ⚡ Implementing memoization for smarter performance 💡 When (and why) to use these transformations in real-world frontend code If you’re diving deeper into React, TypeScript, or just love exploring JavaScript patterns that scale, this post is packed with hands-on insights and aha moments. 📰 Read the full article: https://lnkd.in/dqbuHGq3 💌 Subscribe for more updates: https://lnkd.in/gDA5t-yP #FrontendQueens #WomenInTech #JavaScript #FunctionalProgramming #React #WebDevelopment #TechBlog
To view or add a comment, sign in
-
🚀 Understanding JavaScript Execution Context — The Foundation of How JS Runs! If you’ve ever wondered how JavaScript knows which variables and functions to access during code execution, the answer lies in the concept of Execution Context. An Execution Context is the environment where your code runs. It determines how and where variables, functions, and objects are stored and accessed. There are three main types: 1. 🌍 Global Execution Context (GEC): Created when your script first runs. It sets up the global object and this. 2. ⚙️ Function Execution Context (FEC): Created each time a function is called. Every function has its own execution environment. 3. 🧩 Eval Execution Context: Created when code runs inside eval() (rarely used). Each execution context goes through two phases: Creation Phase: Memory is allocated for variables and functions (hoisting happens here). Execution Phase: Code runs line by line, variables get their actual values, and functions are invoked. #JavaScript #WebDevelopment #Frontend #Coding #Learning #SDE #SoftwareEngineering #ReactJS
To view or add a comment, sign in
-
Just React theory? Here are 3 practical components you'll actually use: 1. SearchBar with Debouncing - Optimizes API calls on user input. 2. Modal/Popup - Reusable for forms, confirmations, and details. 3. Infinite Scroll - Perfect for feeds and data-heavy lists. What's your go-to reusable component? Share below! 👇 #ReactJS #WebDevelopment #JavaScript #Coding #Frontend #SoftwareEngineering #100DaysOfCode #Programming #Tech #Developer
To view or add a comment, sign in
-
JavaScript is good, but TypeScript makes it better! As developers, we spend a lot of time fixing bugs. What if we could prevent most of them before the code even runs? That's where TypeScript comes in. Simply put: TypeScript = JavaScript + "Types". By defining what a variable is (e.g., a 'string' or a 'number'), we ensure we don't make simple mistakes (like trying to add a word to a number). The code editor (like VS Code) alerts us in real-time. For me, adopting TypeScript means: ✅ Writing safer, more reliable code. ✅ Making the code easier to maintain (especially on a team). ✅ Being more productive in the long run. It's a tool I've adopted in my recent projects, and it’s a real game-changer for code quality. What's your favorite feature in TypeScript?" #TypeScript #JavaScript #WebDevelopment #ReactJS #FullStackDeveloper #SoftwareEngineering #Coding #Developer
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