TypeScript Type vs Interface Use interface → For Contracts & Object Structure ✅ Service contracts ✅ Domain models ✅ DTOs ✅ Class implementations export interface PaymentProvider { charge(amount: number): Promise<boolean> refund(id: string): Promise<boolean> } class StripeProvider implements PaymentProvider {} interface User { id: string email: string } 𝗜𝗡𝗧𝗘𝗥𝗙𝗔𝗖𝗘: Use when defining object shape or implementation contract. Use type → For Unions, States & Advanced Types ✅ Union types ✅ Event models ✅ API response wrappers ✅ Utility & composition types type UserRole = "ADMIN" | "USER" | "SUPPORT" type ApiResponse<T> = | { success: true; data: T } | { success: false; error: string } type AdminUser = User & { permissions: string[] } 𝗧𝗬𝗣𝗘: Use when modeling states, variations, or type logic. 🎯 Simple Rule Contract or extendable object → interface Union or advanced typing → type #TypeScript #JavaScript #BackendDevelopment #WebDevelopment #SoftwareArchitecture #CleanCode #NestJS #NodeJS #Programming
TypeScript Interface vs Type: Contracts & Object Structure
More Relevant Posts
-
Understanding the Power of tsconfig.json in TypeScript I spent some time exploring the tsconfig.json file and realized how much control it gives over how our code is compiled and structured. Here are a few key configurations I used and why they matter: 🔹 target: "ESNext" – Allows using the latest JavaScript features without down-leveling them unnecessarily. 🔹 module: "ESNext" – Enables modern ES module syntax, which works seamlessly with modern bundlers. 🔹 declaration: true – Generates .d.ts files, which are extremely important when publishing libraries so other developers get proper TypeScript types. 🔹 jsx: "react-jsx" – Uses the new React JSX transform, removing the need to manually import React in every component. 🔹 strict: true – Enables strict type checking, helping catch potential bugs early during development. 🔹 moduleResolution: "node" – Allows TypeScript to resolve modules the same way Node.js does. 🔹 resolveJsonModule: true – Makes it possible to import JSON files directly into TypeScript. 🔹 outDir: "dist" – Ensures compiled JavaScript and type files are neatly generated in a distribution folder. It’s fascinating how a small configuration file can influence type safety, module handling, library distribution, and developer experience. Currently exploring more around TypeScript configurations, CLI tooling, and modern frontend workflows. #TypeScript #React #JavaScript #WebDevelopment #FrontendDevelopment #DeveloperJourney
To view or add a comment, sign in
-
-
🚀JavaScript is single-threaded… yet Node.js handles thousands of concurrent requests. How? JavaScript is single-threaded. So how does Node.js handle thousands of asynchronous operations like file reads, database calls, timers, and network requests without blocking the application? While learning Node.js internals, I tried to break this down with a simple architecture diagram. JavaScript runs inside the V8 engine and executes code line by line using a single call stack. This means only one piece of JavaScript code runs at a time. But when operations like reading a file, making an API request, or starting a timer happen, Node.js doesn't block the main thread waiting for the result. Instead, these operations are delegated to another layer that interacts with the operating system and manages asynchronous tasks. Once the operation finishes, the result is placed in a queue and executed when the call stack becomes free. This is what makes Node.js capable of handling many concurrent operations efficiently. I drew the architecture to understand the flow: JavaScript (Call Stack) → Node.js APIs → Async I/O Layer → Operating System → Event Loop → Callback Execution Two questions for backend developers: 1: What library powers asynchronous I/O and the event loop in Node.js? 2: Which programming languages are used to build the V8 engine, Node.js runtime, and the async I/O layer behind it? Drop your answers in the comments. #NodeJS #JavaScript #BackendDevelopment #AsyncProgramming #EventLoop #WebDevelopment #Libuv #react #mern
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝗙𝘂𝗻𝗰𝗮𝗶𝗼𝗻𝗮𝗹 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 𝗶𝗻 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 You can simplify your Angular code and reduce bugs by using functional programming principles. Here are some benefits: - Fewer runtime errors - Easier maintenance - Improved performance To get started, focus on these key principles: - Use strict typing to catch errors at compile time - Define explicit contracts between your frontend and backend - Use pure functions to transform data - Create reactive data flows with RxJS Some best practices to keep in mind: - Mark fields as readonly to prevent mutations - Use async pipes to subscribe to observables - Avoid manual subscriptions and memory leaks - Keep your data flow explicit and easy to trace By following these principles and best practices, you can make your Angular code more reliable, efficient, and easier to maintain. Source: https://lnkd.in/gqc67pW3
To view or add a comment, sign in
-
🚨 Node.js is NOT actually single-threaded One of the biggest misconceptions I had early in backend development: “Node.js can only handle one thing at a time.” Not true. Node runs JavaScript on a single thread but under the hood it uses: Event Loop Worker Threads libuv thread pool Meaning: - File system operations - Database queries - Network requests are executed outside the main thread. The real bottleneck isn’t Node itself, it’s CPU-blocking code. 💡 Lesson: Node excels at I/O-heavy systems, not CPU-heavy computation. That’s why companies use Node for APIs but offload heavy processing to workers or services. 💬 Question: What surprised you most when you learned how Node actually works? #NodeJS #BackendEngineering #SystemDesign #JavaScript #FullStackDev #SoftwareEngineering #TechInsights
To view or add a comment, sign in
-
-
🤔 Did you know TypeScript can generate string unions for you? Template literal types let you build new string literal types and expand them into unions automatically. Here are 3 practical examples: 1. API Endpoints: type Version = 'v1' | 'v2' | 'v3'; type Resource = 'users' | 'posts' | 'comments'; type APIEndpoint = `/api/${Version}/${Resource}`; // Results in 9 possible values... 2. Event Naming Patterns: type EventType = 'click' | 'submit' | 'change'; type Component = 'button' | 'form' | 'input'; type EventName = `on${Capitalize<EventType>}${Capitalize<Component>}`; // 'onClickButton' | 'onClickForm' | ... 3. Property Transformation type User = { firstName: string; lastName: string; email: string; }; type ChangeEvent<T> = `${keyof T & string}Changed`; // 'firstNameChanged' | 'lastNameChanged' | 'emailChanged' #TypeScript #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
When frontend and backend applications communicate, they need a structured way to exchange data. One of the most widely used formats for this is JSON. JSON stands for JavaScript Object Notation. It is a lightweight format used to store and transfer data between a client and a server. The reason JSON is so popular is because it is simple, readable, and language independent. A typical JSON structure looks like this: ``` { "name": "John", "email": "john@example.com", "role": "developer" } ``` In a full stack application: • The frontend sends data to the backend in JSON format. • The backend processes the request. • The server sends JSON responses back to the client. For example: A login request might send: email and password → server verifies → response returned in JSON. JSON acts as the bridge that allows different parts of an application to communicate smoothly. Understanding JSON is essential because almost every modern API relies on it. #JSON #WebDevelopment #BackendDevelopment #FullStackDeveloper #Nodejs #APIDesign #MERNStack #SoftwareEngineer #JavaScript #PersonalBranding
To view or add a comment, sign in
-
𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? JavaScript is single-threaded, but it can handle asynchronous operations efficiently using the Event Loop. The Event Loop is a mechanism that allows JavaScript to perform non-blocking operations like API calls, timers, and file reading while still running on a single thread. Here’s how it works: 1️⃣ Call Stack – Executes synchronous JavaScript code. 2️⃣ Web APIs – Handles async operations like "setTimeout", "fetch", and DOM events. 3️⃣ Callback Queue / Microtask Queue – Stores callbacks waiting to be executed. 4️⃣ Event Loop – Continuously checks if the call stack is empty and pushes queued callbacks to the stack for execution. This architecture allows JavaScript to manage asynchronous tasks without blocking the main thread, making it ideal for building fast and scalable web applications. Understanding the Event Loop is essential for mastering Promises, async/await, callbacks, and performance optimization in JavaScript. #JavaScript #EventLoop #WebDevelopment #FrontendDevelopment #NodeJS #AsyncJavaScript #CodingInterview #SoftwareEngineering #FullStackDeveloper #LearnToCode
To view or add a comment, sign in
-
Let, Var, or Any? Don’t break your Angular Type-Safety! 🛡️ If you are moving from JavaScript to Angular, the way you declare variables changes everything. Here is the "Cheat Sheet" for your next Stand-up: 🚫 var (The Ghost): It’s function-scoped and "hoisted." It can cause values to leak out of loops and blocks. In modern Angular (TypeScript), var is effectively deprecated. Stop using it! ✅ let (The Standard): It’s block-scoped. It lives only within the { } where it was born. It makes your logic predictable and clean. Always use let for variables that change, and const for those that don't. ⚠️ any (The Escape Hatch): This isn't about scope—it's about Type. Using any is like saying "I give up" to the TypeScript compiler. You lose all the benefits of bug-catching before your code even runs. Pro-Tip: If you don't know the shape of your data, use unknown instead of any. It forces you to check the type before using it, keeping your app crash-proof! 🚀 Are you still finding any scattered throughout your legacy components, or have you achieved "Strict" mode? Let’s talk about refactoring! 👇 #Angular #TypeScript #JavaScript #WebDevelopment #FrontendEngineering #CodingTips #CleanCode #SoftwareArchitecture
To view or add a comment, sign in
-
-
Today I worked on a small automation project using JavaScript and Node.js. https://lnkd.in/geXynPVJ The script automatically organizes files by: • File type (images, videos, documents, etc.) • File date (year → month → category) Example structure it generates: 2026/ March/ images/ videos/ documents/ Some features I implemented: ✔ Case-insensitive file detection ✔ Automatic folder creation ✔ File collision protection ✔ Fallback category for unknown files ▶️ How to Use Install Node.js node -v Clone the repo git clone https://lnkd.in/gZmYZFwY cd organize-by-date Run the script node organize.js /path/to/folder Example: node organize.js ~/Downloads Done ✅ Files will be organized into: Year/ Month/ images/ videos/ documents/ others/ #JavaScript #NodeJS #Automation #Coding #DeveloperJourney
To view or add a comment, sign in
-
-
🛑 Stop making all your TypeScript interface properties optional. If you use TypeScript, you have probably been tempted to just slap a ? on a property to make the compiler stop yelling at you. id?: string; name?: string; We do this because a User in the database has an id, but a User being submitted in a registration form doesn't have an id yet. So we make it optional to share the same interface. This is a massive trap. 🪤 When you make properties optional, you are destroying your type safety. You will spend the rest of your app writing defensive code: if (user.id !== undefined) { ... }. The Fix: Strict Base Interfaces + Utility Types. ✨ Define your core interface as the absolute, strict truth (no optional fields unless they are truly optional). Then, let TypeScript do the heavy lifting using Omit and Pick. Why this wins: ✅ Zero Guesswork: If a function requires a UserCardProps, you know with 100% certainty that name and email will be there. No undefined checks needed. ✅ Single Source of Truth: If you add a new required property to your base User, your derived utility types automatically inherit it. ✅ Self-Documenting: Reading Omit<User, 'id'> instantly tells the next developer exactly what this object is meant for. Stop fighting the TypeScript compiler. Let Utility Types do the work for you. 🧠 Are you using Pick and Omit, or are you still living in the Optional wild west? 👇 #TypeScript #JavaScript #WebDevelopment #Frontend #ReactJS #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
Explore related topics
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
But this actually is not a fixed rule or something nah? I think it actually varies from team to team. Like where I'm now they use interface when they're making a custom library which will be used later on different applications. But for an application they often strict to just types. However, yeah both type and interface has some limitations.