Let's talk about something quite interesting in TypeScript - 'Indexed Access Types.' In TypeScript, 'Indexed Access Types' let us look up a type by indexing another type. This is similar to how we access a property on an object or an array at runtime. Let’s say we have an 'as const' object, and we want our types to stay perfectly in sync with the values inside it. That’s where 'Indexed Access Types' shine. This means if the original object changes, your derived types update automatically. You can even use 'keyof' with it to extract all possible value types or combine specific keys to build flexible unions. And yes, this is why 'as const' is so useful because it ensures those values are literal types, not widened ones like 'string.' If you try to access a key that doesn’t exist, TypeScript immediately warns you, giving you both type safety and consistency. So far, I talked about ' as const' objects in TypeScript. What if instead of an object, we have an ‘as const’ array? Using 'as const', this array becomes a 'readonly tuple,' and we can use 'Indexed Access Types' to extract types from it the same way we do with objects. We can get the type of a specific element by its index or even create a union type of all the values in the array. Here’s where it gets interesting. If we use 'number' as the index type, TypeScript interprets that as 'all numeric indices', effectively giving us a union of all the element types in the array. That means if our array changes or if elements are added or removed, the derived type automatically reflects those changes. This pattern is incredibly powerful for defining value-driven types that evolve with your code. In short, Indexed Access Types help you create types that truly evolve with your data. #TypeScript #JavaScript #Programming #Development #Coding #WebDevelopment
How Indexed Access Types work in TypeScript
More Relevant Posts
-
In TypeScript, generics play a crucial role when you want to write reusable and type-safe code. They help ensure that your functions, classes, and components work with any data type without losing type safety at compile time. Let's look at some examples. 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗚𝗲𝗻𝗲𝗿𝗶𝗰𝘀: If you define an array without specifying a strict type, TypeScript tries to infer it based on the values you insert. 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗡𝗼𝗿𝗺𝗮𝗹 = ["𝗮", "𝗯", "𝗰", 𝟭]; TypeScript infers the type as "(string | number)[]". This could lead to unexpected behaviour. 𝗪𝗶𝘁𝗵 𝗚𝗲𝗻𝗲𝗿𝗶𝗰𝘀: Let’s define a generic function: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝗧>(𝗮𝗿𝗴𝘀: 𝗔𝗿𝗿𝗮𝘆<𝗧>): 𝗔𝗿𝗿𝗮𝘆<𝗧> { 𝗿𝗲𝘁𝘂𝗿𝗻 𝗮𝗿𝗴𝘀; } In the above function, "T" refers to the data type; it can be a number, string, or any user-defined type. Now let’s invoke the above generic function with the same array "(["a", "b", "c", 1])": 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗚𝗲𝗻𝗲𝗿𝗶𝗰 = 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝘀𝘁𝗿𝗶𝗻𝗴>(["𝗮", "𝗯", "𝗰", 𝟭]); 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 𝘁𝗵𝗿𝗼𝘄𝘀 𝗮𝗻 𝗲𝗿𝗿𝗼𝗿: Type "number" is not assignable to type 'string'. This helps catch the error before your code runs. The proper way to define a type string array using generics: 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗚𝗲𝗻𝗲𝗿𝗶𝗰 = 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝘀𝘁𝗿𝗶𝗻𝗴>(["𝗮", "𝗯", "𝗰"]); 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. Prevent runtime bugs by catching type errors early. 2. Improve code reusability and maintainability. 3. Write flexible, type-safe code. Let’s continue learning about generics in the next post. #typescript #web #javascript #tech #learning
To view or add a comment, sign in
-
-
Over the last few posts, I talked about how TypeScript infers types, how we can override them, and how we can validate them. Now it’s time to connect the dots. There are three main approaches - 1. Type Annotation 2. Type Assertion (as) 3. 'satisfies' operator 1. Type Annotation - You’re telling TypeScript what the type should be. This is something you should use when - 1. You want to define the shape of something upfront. 2. You’re working with function signatures, public APIs, data models, interfaces, etc. 3. You want clarity and explicitness. The downside here is that if you annotate something like an object literal too broadly (e.g., Record<string, ...>), you can lose type inference, especially for literal key names. 2. Type Assertion - You’re overriding TypeScript’s inference and saying - 'Trust me.' This is something you should use when - 1. TypeScript can’t figure out the type, but you know what it is. 2. You’re working with DOM elements or events. 3. You’re dealing with external data (like JSON or API responses). But remember that type assertion does not perform any runtime validation. If you’re wrong, TypeScript won’t save you. 3. 'satisfies' operator - You want to validate and preserve inference. 'satisfies' checks that a value conforms to a given type, without changing the inferred type. This means, Literal keys stay literal, values stay precise, and extra properties are caught as errors. So, we get the best of both worlds, meaning the object must match a required shape but inference stays as detailed as possible. This is a good option for things like configuration objects, constant maps, enum-like value objects etc. The bottom-line is that TypeScript gives you these tools for a reason. The real skill is in knowing which one to reach for depending on the situation. #TypeScript #Coding #JavaScript #WebDevelopment #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 Understanding the Core Type Differences in TypeScript TypeScript provides several special types that describe different states of data — and understanding them well is key to writing predictable, safe code. -(undefined): represents a variable that has been declared but not yet assigned a value. It means “missing” or “not initialized.” -(null): represents the intentional absence of a value. It means “we know there’s nothing here.” While undefined often happens naturally, null is explicitly set. -(any): disables all type checking. It’s the most flexible — and the most dangerous — type. It says “this could be anything,” which removes TypeScript’s safety guarantees. -(unknown): is the safer alternative to any. It can hold any value, but you must verify the type before using it. It enforces caution when working with dynamic data. -(void): indicates the absence of a return value, commonly used for functions that don’t return anything. It tells the developer that “this function performs an action, not a computation.” -(never): represents a state that can never occur. It’s used for functions that never return (like those that throw errors or run infinitely). It signals that a certain path in the code should be unreachable. In TypeScript’s type hierarchy, (any) and (unknown) sit at the top — they can represent any value. (never) sits at the bottom — it represents no value at all. Mastering these distinctions helps you reason more clearly about your data, enforce intent in your code, and leverage TypeScript for what it truly is: a language for clarity and correctness. #TypeScript #SoftwareEngineering #WebDevelopment #CodingBestPractices #JavaScript
To view or add a comment, sign in
-
-
🛡️ The "Any" Trap: Where TypeScript Armor Fails I recently reviewed some TypeScript code from a company I was consulting for, and while the intention was right—they were using TypeScript—the execution was, well, accurately described by this meme. We adopt TypeScript for its safety net and the confidence that its static type checking provides. It's the armor protecting us from runtime errors and making refactoring manageable. But every time we use the any keyword, we are essentially taking off that armor and giving the compiler a hall pass. Why relying on any defeats the purpose: Bypassing Type Safety: any tells TypeScript, "Stop checking this." It lets you assign anything to it and call any method on it, effectively turning that section of your code back into plain JavaScript. You lose IntelliSense, compile-time error checking, and code confidence. Hiding Real Issues: Using any often means a developer couldn't easily figure out the correct type. Instead of forcing them to solve the type challenge, any allows the issue to be deferred until runtime, which is the exact scenario TypeScript is meant to prevent. Damaging Maintainability: When a new developer inherits the code, seeing any gives them no context about the data structure they are working with, increasing their cognitive load and the chance of introducing bugs. If you find yourself reaching for any frequently, consider alternatives like generic types, utility types (Partial, Pick), or a simple unknown (which forces you to perform a type check before using it). Don't let the any arrow pierce your project's armor! Are you strict about avoiding any, or do you find it necessary in certain interop scenarios (like dealing with external libraries)? Let me know your rules for the any keyword! 👇
To view or add a comment, sign in
-
-
Ever encountered a runtime error that took hours to debug? TypeScript can be a game changer in preventing those moments. TypeScript isn’t just JavaScript with types—it’s a powerful tool that introduces static typing, making your code more predictable and easier to maintain. One practical tip: start by gradually adopting TypeScript through `--allowJs` and `--checkJs` flags if you have an existing JavaScript codebase. This incremental approach helps catch errors early without a massive rewrite. For example, explicit interfaces for API responses can highlight mismatches before they reach production, saving time and frustration. Another insight: leveraging TypeScript's type inference reduces boilerplate while still providing robust type safety. This balance keeps development efficient but safe, especially when working with complex data structures. Ultimately, TypeScript encourages a mindset shift—from reactive bug fixing to proactive error prevention. For developers, this means writing clearer code that scales better and collaborates more smoothly across teams. Have you experienced the benefits of TypeScript in your projects? How has it changed your workflow? #TypeScript #JavaScript #WebDevelopment #StaticTyping #DeveloperExperience #CodeQuality
To view or add a comment, sign in
-
🧠💭 Wait… TypeScript just climbed to the top on GitHub? I had to double-check the stats. But yes TypeScript is officially one of the most dominant languages on GitHub right now. A language that didn’t even exist a decade ago is now standing shoulder-to-shoulder with JavaScript and Python. So what happened? 🤔 Let’s unpack it 👇 💡 1. Developers are tired of “mystery bugs.” We’ve all been there an undefined variable at runtime, a silent failure that costs hours. TypeScript came along and said, “What if we caught these before running the code?” ⚙️ 2. It scales better than plain JavaScript. When you’re working solo, JS feels fine. But when 50+ devs collaborate on a massive codebase, type safety becomes your best friend. 🌐 3. The ecosystem shifted. Frameworks like React, Next.js, and Node tools now treat TypeScript as first-class. It’s no longer an optional extra it’s the new normal. 🔥 4. GitHub numbers don’t lie. TypeScript projects are surging not just in web apps, but backend systems, AI tools, and even edge computing projects. It’s wild to see how far it’s come. Now I’m curious 👇 Do you think TypeScript will replace JavaScript someday or will both co-exist like C and C++? #TypeScript #JavaScript #GitHubTrends #Programming #WebDevelopment #DeveloperCommunity #Coding
To view or add a comment, sign in
-
-
If you’ve ever explored the 'node_modules' folder or peeked inside a TypeScript library, you’ve probably noticed files with the '.d.ts' extension and wondered - 'What are these d.ts files actually for?' These '.d.ts' files are known as 'Declaration Files' in TypeScript. A declaration file (.d.ts) is a file that contains type definitions only and no executable code. It’s how TypeScript learns the shape of code that might be written in JavaScript. Think of it like documentation that TypeScript can read. It describes things like - - What functions exist, - What parameters they take, - What they return, - What classes, constants, or types are available. But it does not include any implementation, just the type information. But why do we need declaration files? Because not all JavaScript libraries are written in TypeScript. So when you import a JS library, TypeScript has no idea what types it exposes, unless there’s a '.d.ts' file telling it. That’s how your editor magically knows what methods and properties exist, and even shows autocomplete suggestions, even if the library itself is just JavaScript. Many libraries written in TypeScript bundle their own '.d.ts' files. Also, you must've seen or used npm packages with names starting with '@types/...'. These are actually from the 'DefinitelyTyped' project which is an open-source project that serves as a central repository for TypeScript type definitions for existing JavaScript libraries. Finally, you can also write your own '.d.ts' files to describe your JS modules, global variables, or extend existing types. So, when should you write one? You’d typically create your own declaration file when - 1. You’re working with plain JS and want TypeScript autocompletion 2. You’re writing a TypeScript library and want consumers to get type safety 3. You’re using a third-party JS library without type definitions. So next time you see a '.d.ts' file, remember - 1. It’s not something you run. 2. It’s something that helps TypeScript understand what’s running. #TypeScript #JavaScript #Coding #Programming #WebDevelopment
To view or add a comment, sign in
-
-
I Spent 2 Days Migrating to TypeScript So I Could Write JavaScript Anyway Congratulations! You've adopted TypeScript. Now you're writing JavaScript with commitment issues. Let me paint you a picture: your team had The Meeting. Someone said " type safety " while gesturing vaguely at a stack trace. Someone else mentioned " developer experience " after their third coffee. Everyone nodded like they understood what that meant. You migrated your codebase, spent two days fixing config files, added typescript to your dependencies, and updated your LinkedIn. Then you wrote this masterpiece: const data: any = await fetchUserData(); Chef's kiss. Beautiful. You've taken a language designed to catch bugs at compile time and told it "nah, surprise me at runtime." It's like buying a seatbelt and wearing it as a scarf. TypeScript's whole thing is preventing undefined is not a function from ruining your Thursday afternoon. But any is the " I trust the universe " button—and you're mashing it like it owes you money. The compiler isn't fooled. Your IDE isn't fooled. And t https://lnkd.in/gHBxucF2
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