The best way to set up TypeScript in a Node.js project (save this for future) While starting with TypeScript in Node.js, the setup steps can feel confusing if you don't know why each command is used. Here's the clean workflow I follow. 1. Initialize the project npm init -y This creates a package.json file to manage dependencies and scripts. 2. Install TypeScript as a dev dependency npm i typescript --save-dev Why not install it as a normal dependency? Because TypeScript is only a development tool. Node.js and browsers run JavaScript, not TypeScript. Installing it as a dev dependency keeps the production build smaller. 3. Create the TypeScript configuration npx tsc --init This generates tsconfig.json which controls how TypeScript compiles the project. 4. Organize your project structure Inside tsconfig.json uncomment: "rootDir": "./src" "outDir": "./dist" Now all your TypeScript code will live inside ./src and the compiled JavaScript will go into ./dist. This keeps the project structure clean. 5. Create a .gitignore npx gitignore Node This prevents committing unnecessary files like node_modules and build outputs. 6. Compile TypeScript npx tsc This converts .ts files into .js files so Node.js can execute them. The problem: Every time you change the code, you would have to compile TypeScript again manually. 7. To solve this we can use tsc-watch. npm i tsc-watch -D 8. Update scripts in package.json "scripts": { "dev": "tsc-watch --onSuccess "node dist/main.js"" } 9. Run the project npm run dev Now whenever you save a file: TypeScript automatically compiles and Node runs the updated code. Commands summary: npm init -y npm i typescript --save-dev npx tsc --init (uncomment rootDir and outDir in tsconfig.json) npx gitignore Node npm i tsc-watch -D (update scripts in package.json) npm run dev If you're learning Node.js with TypeScript, this setup will save you a lot of time. #nodejs #typescript #backenddevelopment #javascript #webdevelopment #chaicode #chaiaurcode Hitesh Choudhary
Setting up TypeScript in Node.js Project
More Relevant Posts
-
TypeScript saved my project last week. Not from a bug. From a bad decision I was about to make. I was refactoring an API response type. Midway through, TypeScript started screaming across 14 files. My first reaction: annoying. My second reaction: wait — these are all the places that would have broken silently in JavaScript. This is what people miss about TypeScript: It's not about catching bugs at compile time. It's about making your architecture visible. When you change a type, and 14 files complain — that's your dependency graph revealing itself. TypeScript is documentation that enforces itself. 3 TypeScript patterns I use on every NestJS + Next.js project: 1. Shared DTO types between frontend and backend → One source of truth. Zero API contract drift. 2. Discriminated unions for API response states → type Result = {status:'ok',data:T} | {status:'error',message:string} → No more checking res.data && !res.error 3. Branded types for IDs → type UserId = string & {__brand:'UserId'} → You can never pass an OrderId where a UserId is expected TypeScript is not a linter. It's a co-architect. What's your most-used TypeScript pattern? Drop it below. #TypeScript #NestJS #NextJS #BackendDevelopment #SoftwareArchitecture #FullStackEngineer #WebDevelopment #CleanCode
To view or add a comment, sign in
-
-
𝗧𝗮𝗸𝗲 𝗬𝗼𝘂𝗿 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗸𝗶𝗹𝗹𝘀 𝗧𝗼 𝗧𝗵𝗲 𝗡𝗲𝗫𝗧 𝗟𝗲𝗩𝗲𝗟 TypeScript is now the standard for building robust JavaScript applications. But many developers only use the basic types. - string - number - boolean TypeScript's true power lies in its advanced type features. These features can prevent bugs and make your code more maintainable. Let's look at an example. You're working with a user object that can be in different states. - loading - authenticated - unauthenticated You can use discriminated unions to solve this problem. - type LoadingUser = { status: 'loading'; } - type AuthenticatedUser = { status: 'authenticated'; id: string; name: string; email: string; } - type UnauthenticatedUser = { status: 'unauthenticated'; } - type User = LoadingUser | AuthenticatedUser | UnauthenticatedUser; TypeScript now understands the relationship between status and properties. You can also use conditional types to create types that change based on conditions. - type IsString<T> = T extends string ? true : false; Mapped types let you create new types by transforming properties of existing types. - type Partial<T> = { [P in keyof T]?: T[P]; } Your challenge is to identify one place in your codebase where you're using optional properties to represent different states, and refactor it using discriminated unions. Share your experience in the comments below. Source: https://lnkd.in/gbZSMQTA
To view or add a comment, sign in
-
Today I was fixing a bug in a backend service built with Express.js (JavaScript). The backend was calling 4 external APIs, and as usual with JavaScript, we had no idea what the exact response structure would be until runtime. So debugging looked like this: console.log(response) console.log(response.data) console.log(response.data?.something) Over and over again. Then I thought — this is exactly where TypeScript shines. If the same code was written in TypeScript, we could define response types like: interface ApiResponse { userId: string status: string data: { name: string email: string } } Now the benefits become obvious: • Autocomplete for API response fields • Instant type errors during development • No need for endless console logs • Easier debugging • Much better code readability • Safer refactoring When you're working with multiple APIs, complex responses, and growing codebases, TypeScript stops being optional — it becomes a superpower. JavaScript is powerful, but TypeScript adds clarity and confidence. After today, I’m even more convinced: TypeScript is not just "JavaScript with types". It's JavaScript with guardrails. #TypeScript #JavaScript #BackendDevelopment #NodeJS #ExpressJS #WebDevelopment #Developers
To view or add a comment, sign in
-
🚫 any is TypeScript's escape hatch. And most of us use it way too often. Every time you type any, you're telling TypeScript: "Stop helping me here." Here are the 4 types I reach for instead 👇 1. unknown — the safe version of any When you don't know the type upfront (API responses, JSON parsing), use unknown. It forces you to narrow the type before using it. TypeScript keeps protecting you. 2. never — for exhaustive checks Use it in switch statements to catch unhandled cases at compile time. If you add a new union member and forget to handle it, TypeScript errors immediately — not in production. 3. Record<K, V> — for typed dictionaries Instead of { [key: string]: any }, write Record<string, User>. Now your values are typed and your IDE actually helps you. 4. Union types A | B — enumerate what's valid Don't loosen the type — enumerate exactly what's allowed. type Status = 'loading' | 'success' | 'error' is infinitely better than string. The rule I follow: → If the type is truly uncertain → unknown → If a case should never happen → never → If it's a key-value map → Record<K,V> → If it's one of N values → union type any has maybe 2 legitimate use cases. Everything else has a better option. Which of these do you find yourself using most? 👇 #TypeScript #JavaScript #WebDevelopment #CleanCode #Frontend
To view or add a comment, sign in
-
-
🚀 Understanding Node.js Internals: Event Loop & Thread Pool This week, I took a deeper dive into how Node.js actually works behind the scenes — and it completely changed how I think about asynchronous code. 🔹 JavaScript in Node.js runs on a single thread 🔹 Yet it handles multiple tasks efficiently using the Event Loop 🔹 Heavy operations are offloaded to the Thread Pool (via libuv) Some key takeaways: Event Loop manages execution in phases (Timers, I/O, setImmediate, etc.) setTimeout(0) is not truly immediate setImmediate() behaves differently inside vs outside I/O process.nextTick() runs before the event loop even starts Understanding these concepts makes async behavior much more predictable and helps write better backend code. Would love to hear your thoughts or corrections 🙌! Blog Link : https://lnkd.in/gxBA4DeT #JavaScript #WebDev #LearnInPublic #Blog #libuv #EventLoop #ThreadPool #ChaiCode Thanks to Hitesh Choudhary, Piyush Garg, Jay Kadlag, Akash Kadlag for guidance 😊
To view or add a comment, sign in
-
-
Vite is both a development server and a build tool for TypeScript and JavaScript applications, with support for hot module replacement (HMR), which updates code without a full page reload
To view or add a comment, sign in
-
When I first switched from JavaScript to TypeScript, I did what most devs do: I just added types everywhere and called it a day. ❌ type name = string type age = number type user = any ← this was my biggest mistake Using "any" completely defeats the purpose of TypeScript. You're just writing JavaScript with extra steps. Here's what changed everything for me: 🔹 Use "unknown" instead of "any" — it forces you to handle types safely 🔹 Use Union types to model real-world data: type Status = 'active' | 'inactive' | 'pending' 🔹 Use "as const" to lock down literal values and stop magic strings 🔹 Let TypeScript INFER types when it can — don't over-annotate 🔹 Use Utility Types (Partial<T>, Pick<T>, Omit<T>) — they save hundreds of lines The moment I stopped fighting TypeScript and started thinking in types, my code quality jumped overnight. TypeScript isn't just about catching bugs. It's about making your intent clear to every developer who reads your code after you. What's the one TypeScript trick that levelled you up? 👇 #TypeScript #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #MERN #CleanCode
To view or add a comment, sign in
-
𝐒𝐰𝐢𝐭𝐜𝐡𝐞𝐝 𝐭𝐨 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭. 𝐏𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 𝐁𝐮𝐠𝐬 𝐃𝐫𝐨𝐩𝐩𝐞𝐝 𝟕𝟎%. 🎯 My Express API was in JavaScript. "Types are just extra work," I thought. 𝐓𝐡𝐞 𝐈𝐦𝐩𝐚𝐜𝐭: Before TypeScript: - 10-15 production bugs per month - Most were type-related errors - "undefined is not a function" 😤 After TypeScript: - 1-2 production bugs per month - Caught 70% of bugs at compile time - No more "cannot read property of undefined" 𝐖𝐡𝐚𝐭 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭 𝐂𝐚𝐮𝐠𝐡𝐭: ✅ Wrong function parameters ✅ Typos in property names ✅ Missing required fields ✅ Wrong return types ✅ Null/undefined handling All BEFORE code reached production. 𝐓𝐡𝐞 𝐁𝐨𝐧𝐮𝐬: Better autocomplete in VS Code Refactoring became safe (rename all references) New team members onboard faster (types = documentation) 𝐖𝐡𝐚𝐭 𝐈 𝐋𝐞𝐚𝐫𝐧𝐞𝐝: "Extra work" in development = Less work in production 5 minutes adding types > 2 hours debugging at 2 AM TypeScript isn't about being fancy. It's about shipping code that works. 𝐓𝐡𝐞 𝐭𝐫𝐚𝐝𝐞-𝐨𝐟𝐟: Initial setup: 1 day (adding types to existing Express app) Time saved: Countless hours of debugging Worth it? Absolutely. 𝐓𝐡𝐞 𝐭𝐚𝐤𝐞𝐚𝐰𝐚𝐲: JavaScript: Fast to write, slow to debug TypeScript: Slower to write, fast to ship Production stability > Development speed Still writing Node/Express in vanilla JS? Give TypeScript a shot. Your future self will thank you. #TypeScript #JavaScript #NodeJS #Express #Backend #WebDev #TodayILearned #ProductionBugs #LessonsLearned #Coding
To view or add a comment, sign in
-
Why Can’t I Use 'super.variable' in TypeScript? (Simple Explanation) I recently got confused by something in TypeScript 👇 I tried to access a parent class property using 'super.variable'… and it didn’t work. 💡 Here’s the simple reason: 👉 'super' only works with **methods**, not **properties** So: * 'super.method()' ✅ works * 'super.variable'❌ doesn’t work --- 🔍 Why? In JavaScript/TypeScript: * Methods are stored in something called the *prototype* * Properties (variables) are usually stored directly in the object (inside the constructor) 'super' looks at the **parent’s prototype**, so it can find methods - but not properties. --- 💡 Example: class Parent { num:number = 10; getValue() { return this.num; } } class Child extends Parent { num:number = 30; print() { console.log(super.getValue()); // ✅ works console.log(this.num); // ✅ correct way - Print overriden value console.log(super.num); // ❌ undefined } } --- ✅ Takeaway: If you want to access a parent property, just use 'this.variable' --- If you're learning TypeScript or JavaScript, this is one of those small things that can be confusing at first 😅 Did this ever confuse you too? #JavaScript #TypeScript #Beginners #WebDevelopment
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗲𝗻𝗲𝗳𝗶𝗍𝘀 𝗢𝗳 𝗨𝘀𝗶𝗻𝗴 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻 𝗡𝗼𝗱𝗲.𝗷𝘀 You can run JavaScript on the server with Node.js and Express.js. TypeScript is JavaScript with a type system. This means you can write safer server-side code. Let's look at a common issue with JavaScript: - JavaScript does not warn you about incorrect data types - This can cause bugs or crash your application TypeScript fixes this: - Prevents runtime errors - Strong type safety - Better code readability - Improved IDE autocomplete - Safer refactoring - Easier collaboration To start using TypeScript: - Install the required dependencies - Initialize the TypeScript configuration Example project structure: - project - src - server.ts - dist - tsconfig.json - package.json TypeScript needs type definitions for libraries written in JavaScript. You can install them using npm. You can safely import Express with full type support: - Import express from "express" - Rename your server file to server.ts Example Express server written in TypeScript: - Import express and types - Create an Express app - Define routes with type safety Interfaces define the structure of objects: - Prevents invalid object structures - Improves readability - Helps maintain consistent data models You can define a consistent response structure: - Benefits include consistent API responses and easier frontend integration Source: https://lnkd.in/gkcWZMu2
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