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
How TypeScript's 'Evolving any' works
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
⚙️ Ever wondered how JavaScript actually executes your code behind the scenes? 🤔 It’s not magic — it’s how the engine works! 🚀 👉 The JavaScript Engine (like V8) runs your code in two main phases: 1️⃣ Memory Creation Phase – Variables and functions get allocated in memory. 2️⃣ Execution Phase – Code runs line by line inside the Call Stack. 🧠 When asynchronous tasks (like setTimeout, API calls, or Promises) come in — they move to the Web APIs, then to the Callback Queue / Microtask Queue, and finally back to the Call Stack through the Event Loop. That’s the secret sauce of how JavaScript handles concurrency and non-blocking execution so smoothly! 💫 #javascript #webdev #frontend #coding #softwareengineering #reactjs #nodejs #programming #developers #typescript #LearningEveryday
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
-
Ever used ANY in TypeScript just to silence that red error? 😅 I’ve been there. At first, ANY felt like a lifesaver — no type errors, no complaints. Until one day, a number turned into a string, a string into an object, and my code broke at the worst possible time. 😬 Then I discovered UNKNOWN. Unlike ANY, it doesn’t trust blindly — it asks questions first. It’s like a teammate who double-checks before merging your PR — a little strict, but saves you from disaster. 😉 What I learned: any = quick peace, later chaos. unknown = small checks, big safety. TypeScript isn’t limiting JavaScript — it makes it smarter, safer, and cleaner. Now, I let TypeScript guide me, because sometimes the best debugging tool is the type warning you didn’t ignore. #TypeScript #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #CleanCode #Programming #CodeBetter #SoftwareDevelopment
To view or add a comment, sign in
-
JavaScript or TypeScript — which one should you really learn first? Here’s the simple roadmap no one explains clearly 👇 🧭 Step 1 – Learn JavaScript first. Understand the core: variables, functions, objects, arrays, and async logic. Without this, TypeScript will feel like a wall. ⚙️ Step 2 – Feel the pain. After building a few projects, you’ll notice JS doesn’t warn you about errors until it’s too late. That’s where TypeScript shines. 💡 Step 3 – Move to TypeScript. It adds types to your JS — making your code more predictable, scalable, and easier to debug. 📈 When to use each: Use JavaScript for quick prototypes or small scripts. Use TypeScript for large, long-term projects, especially with teams. Mastering both will make you unstoppable in modern development. 👉 Which one are you using right now — JS or TS? #JavaScript #TypeScript #Programming #CareerGrowth #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Did you know? In JavaScript, setTimeout(..., 0) doesn’t actually run immediately. It runs after all Promises and await calls — even if the delay is 0ms 🧠 Why? Because JS runs all microtasks (like Promises and await) before moving on to macrotasks (like setTimeout, setInterval, etc.). 💡 Takeaway: Understanding the event loop helps you fix async bugs and write smoother, predictable code. #JavaScript #Coding #WebDevelopment #EventLoop #AsyncProgramming #CodeTips #Developers #Learning #letsLearnWithPrateek #Day7 Here’s proof 👇
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
-
🚀 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
-
-
Accidentally Discovered Something Cool in JavaScript! 😎 While working on some JavaScript code, I accidentally came across the ! and !! operators - and it turned out to be a really interesting find 😄 At first, I was confused 🤔 but after a bit of testing, it all made sense! - The ! (NOT) operator converts true -> false, and vice versa. - The !! (Double NOT) operator converts any value into its boolean equivalent value and its great for checking if something is truthy or falsy. This tiny trick makes conditions cleaner and helps when validating inputs or checking existence of values in JavaScript. Tiny discoveries like these remind me how fun it is to explore and learn JavaScript every day! 😊 . . . . . . . #WebDevelopment #JavaScript #Frontend #CodingJourney #LearningByDoing #Developer #Coding #LearningToCode #FrontendDevelopment #DevelopersCommunity #CodingTips #CodeWithMe #CleanCode #CodeBetter #DevLife
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