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
Kishore Prabhu’s Post
More Relevant Posts
-
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
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
-
-
💡 Why Switching From JavaScript Backend Isn’t Always Necessary Many developers assume that building a high-performance, scalable backend requires moving to Java or Go. The truth? Modern JavaScript frameworks like Fastify are more than capable of handling serious workloads—if used correctly. Here’s a high-level perspective: ⚡ Performance Is Often Enough Fastify is optimized for speed, with minimal overhead and fast JSON serialization. For most APIs, web services, and microservices, its performance is comparable to compiled languages. Only extremely CPU-intensive or low-latency systems might truly benefit from Go or Java. 🛠️ Maintainability & Safety Are Achievable With TypeScript + schema validation, JS backends can be predictable, safe, and robust. Strong typing and clear contracts are no longer exclusive to Java or Go—though they still have stricter compiler-level guarantees. 📦 Scalable Architecture Matters Most Fastify’s modular plugin system allows clean, maintainable code that can grow from small apps to large-scale services. Real scalability depends on architecture, not just language choice. 💡 Developer Velocity Counts Switching to Java or Go comes with a learning curve, setup overhead, and slower iteration. Staying in JS lets teams move fast, iterate frequently, and reduce context switching—all while building production-grade backends. ✅ Bottom line: You don’t need to leave JavaScript to build robust, scalable backends. With the right tools, architecture, and practices, JS can deliver the speed, maintainability, and developer productivity many think only Java or Go can provide. #JavaScriptBackend #Fastify #NodeJS #TypeScript #BackendDevelopment #ScalableArchitecture #WebDevelopment #APIPerformance #DeveloperProductivity #ModernJS
To view or add a comment, sign in
-
-
This article by Sumit Saha explores the concept of multi-threading in Node.js using worker threads, a significant approach for handling concurrent operations. I found it interesting that while JavaScript is traditionally single-threaded, implementing worker threads can greatly enhance performance for computationally intensive tasks. What strategies have you used to optimize performance in your Node.js applications? Read more: https://lnkd.in/dpVdJir4
To view or add a comment, sign in
-
💻 Day 3 of My 30-Day Backend Development & Coding Journey 🚀 Today was all about making my backend come alive visually — I learned how to connect server-side logic with dynamic HTML pages using EJS (Embedded JavaScript Templates) ⚙️💡 It’s amazing how templating helps render data dynamically — instead of sending plain text responses, I can now serve pages that update with real data 🤩 🧠 Topics I Covered Today: 🔹 What is Templating? — A way to generate dynamic HTML using logic and variables 🧩 🔹 Using EJS — The most popular templating engine for Express.js 💻 🔹 Views Directory — Where all .ejs templates are stored 📂 🔹 Interpolation Syntax — <%= %> to embed variables directly into HTML 🧠 🔹 Passing Data to EJS — Sending data from the backend to the frontend using res.render() Each day I’m realizing — backend development isn’t just about servers and APIs, it’s also about how data flows beautifully to the frontend 🖥️ Tomorrow I’ll explore partials, layouts, and reusability in EJS to write cleaner code 💪 #Day3 #30DaysOfCode #BackendDevelopment #NodeJS #EJS #ExpressJS #LearningInPublic #CodingJourney #Developers #WebDevelopment
To view or add a comment, sign in
-
-
🚀 JavaScript Records & Tuples - The Future of Immutable Data! 🧠 Modern JavaScript keeps evolving - and Records & Tuples are one of the most exciting new additions coming to the language! 💥 💡 What are they? They’re immutable versions of objects and arrays - meaning once created, they can’t be changed. Think of them as “frozen” data structures that improve safety and predictability. 👉 Example: const user = #{ name: "John", age: 27 }; const skills = #["React", "JS", "RN"]; Both user and skills are now immutable — no accidental mutations! 🔒 ✅ Why it matters: • Prevents unwanted side effects • Improves performance in large apps • Perfect for functional programming • Makes debugging easier The future of JS is getting more predictable and developer-friendly — and this is a big step in that direction! 🚀 #JavaScript #WebDevelopment #ReactNative #ReactJS #Frontend #TypeScript #CodingTips #ImmutableData #ESNext #ModernJavaScript #Developer #linkedin #typeScript
To view or add a comment, sign in
-
🔥 Day 33 of #100DaysLearningChallenge 🧠 Topic: How to Handle JSON Files in JavaScript (Node.js) 📘 Overview Today, I learned how to read and access data from a JSON file using JavaScript in Node.js. JSON (JavaScript Object Notation) is one of the most common formats for storing and exchanging data — and knowing how to handle it in JS is super useful! 📂 What the JSON File Contains: ✅ Simple values → strings, numbers, booleans ✅ Nested objects → e.g. a client object with multiple properties ✅ Arrays → lists of numbers or strings ✅ Arrays of objects → e.g. a score array containing multiple records ⚙️ How It Works 1️⃣ Loading the JSON File We can use require() in Node.js to import the JSON file. It automatically parses it and returns a JavaScript object. ✔️ typeof data → returns "object" 2️⃣ Iterating Through the Data We loop through each property using for...in. Depending on the type of data, we handle it differently: Simple values (string, number, boolean): print key-value pairs Arrays: If it contains numbers → print each number If it contains objects → use a nested loop to access each property Nested objects: loop through their internal keys and values 💡 Key Concepts Learned 🔹 Type Checking: typeof helps detect if a value is a primitive or object 🔹 Array Detection: instanceof Array distinguishes arrays from objects 🔹 Nested Loops: Used for deep data traversal 🔹 Error Handling: Always good to wrap in try-catch for safety 🧩 Expected Output Example: name - Rohan age - 34 is_active - true id - A101 username - rohan123 30 40 25 60 f1 - 23 f2 - 25 f3 - 27 ... This method allows reading all data — even deeply nested structures — easily! 🙏 Special Thanks to Saurabh Shukla Sir for explaining everything so clearly and practically. 💻 My Code: https://lnkd.in/d4TnHZGj) #100DaysLearningChallenge #JavaScript #NodeJS #JSON #WebDevelopment #Backend #Programming #DataHandling #CodingJourney
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
-
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