🚀 Day 15– TypeScript: What, Why & How (With Real-Time Thinking) Today I went deeper into understanding TypeScript — not just as a language, but as a practical tool used in real projects. 🔹 What is TypeScript? TypeScript is a superset of JavaScript developed by Microsoft that adds static typing. 👉 But in real development, it acts like a safety layer on top of JavaScript that helps prevent mistakes before the code even runs. 🔹 Why TypeScript is Important (Real Problems I Noticed) While working on applications, these are very common issues: ❌ API response structure is unclear ❌ Accessing undefined properties causes runtime errors ❌ Large code becomes hard to understand for new developers ❌ Small changes break existing functionality 👉 TypeScript helps solve these problems by: ✔️ Enforcing strict types for data ✔️ Catching errors during development ✔️ Making code self-documenting ✔️ Improving maintainability in large-scale applications 🔹 Basic Data Types (Foundation) let name: string = "Keerthi"; let age: number = 25; let isActive: boolean = true; let skills: string[] = ["Java", "TypeScript"]; let user: [string, number] = ["Keerthi", 25]; // tuple 👉 These types make the code more predictable and avoid mistakes. 🔹 Real Problem: Unclear API Response const user = getUser(); console.log(user.name); // ❌ risky ✔️ With TypeScript: interface User { name: string; age: number; } const user: User = getUser(); 🔹 Function Safety function add(a: number, b: number): number { return a + b; } // add(10, "20") ❌ Error 🔹 UI State Handling type Status = "loading" | "success" | "error"; let status: Status = "loading"; 👉 Prevents invalid values 🔹 Real-Time Scenarios Where I Can Use TypeScript 📌 API Integration Defining interfaces ensures I know exactly what fields are coming from backend. 📌 Form Handling Optional properties help when some fields are not mandatory. 📌 UI State Management Using fixed types for states like "loading" | "success" | "error" avoids invalid states. 📌 Function Design Clearly defining input and return types avoids misuse of functions. 📌 Team Collaboration Other developers can understand the structure without extra documentation. 🔹 How TypeScript Works TypeScript (.ts) → Compiled using tsc → JavaScript (.js) → Runs in browser/node 👉 Important point: Browsers understand only JavaScript, not TypeScript. 🔹 Small Example Without TypeScript: We might accidentally pass wrong data and only find issues at runtime. With TypeScript: We get immediate errors during development, which saves debugging time. 🔹 My Key Learning TypeScript is not just about adding types — it’s about writing code that is: ✔️ Safer ✔️ Easier to understand ✔️ Easier to maintain ✔️ More reliable in real-world applications #TypeScript #JavaScript #FrontendDevelopment #InterviewPreparation #LearningJourney #SoftwareDevelopment
TypeScript: Preventing Mistakes in Real-World Development
More Relevant Posts
-
𝗧𝘆𝗽𝗲𝘀𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲𝘀: 𝗕𝗲𝘆𝗼𝗻𝗱 𝗕𝗮𝘀𝗶𝗰𝘀 You write TypeScript. You avoid any types. You see green squiggles. But errors happen at runtime. TypeScript missed them. Many developers face this. Basic types seem enough. But TypeScript can catch more. It makes code stronger. Use these patterns. - Branded types: Give strings unique names. UserId and Email are both strings but different types. This stops mix-ups. type UserId = string & { brand: unique symbol }; function createUserId(id: string): UserId { return id as UserId; } function sendEmail(userId: UserId, email: Email) {} sendEmail(createUserId('123'), 'test@example.com'); // Error - Template literals and infer: Parse string patterns. Extract parts from paths. type Route = `/users/${string}/posts/${string}`; type Params<T> = T extends `/users/${infer U}/posts/${infer P}` ? {userId: U; postId: P} : never; Params<'/users/alice/posts/99'> is {userId: 'alice', postId: '99'} - as const: Make objects deeply immutable. Get exact types. const config = { env: 'production', retries: 3 } as const; // config.env is 'production' not string - keyof and mapped types: Generate types from keys. Create Partial or Readonly. type PartialUser = { [K in keyof User]?: User[K]; }; type UserUpdate = { [K in keyof User as K extends 'id' ? never : K]?: User[K]; }; - Conditional types: Add logic to types. type Awaited<T> = T extends Promise<infer U> ? U : T; type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T; Build a type-safe API client. const API_ROUTES = { getUser: '/users/:id' } as const; type ParamsFor<K extends keyof typeof API_ROUTES> = Record<ExtractParamNames<typeof API_ROUTES[K]>, string>; async function fetchFromApi<K extends keyof typeof API_ROUTES>(key: K, params: ParamsFor<K>) { // Fetch with correct params } This finds param errors early. Advanced TypeScript shifts your mindset. Design types before code. Start with one pattern. Apply it today. Catch bugs early. Refactor with confidence. What patterns do you use? Share your stories below. Source: https://lnkd.in/g__X8SbJ
To view or add a comment, sign in
-
**10 useful TypeScript tricks** . TypeScript has become a core part of modern React development. Beyond basic typing, it provides powerful utilities that make code **safer, cleaner, and more maintainable**. 1️⃣ `Partial<T>` – Optional Properties Useful for update forms or API patches. interface User { id: number name: string email: string } type UpdateUser = Partial<User> -------------- 2️⃣ `Pick<T, K>` – Select Specific Fields type UserPreview = Pick<User, "id" | "name"> Great when a component only needs **specific data**. ------------- 3️⃣ `Omit<T, K>` – Remove Fields type PublicUser = Omit<User, "email"> Useful for hiding **private fields**. ----------------- 4️⃣ `Readonly<T>` – Immutable Data const user: Readonly<User> = { id: 1, name: "John", email: "john@example.com" } Prevents accidental state mutation. -------------- 5️⃣ `Record<K, T>` – Dynamic Object Types type Roles = Record<string, string> const userRoles: Roles = { admin: "full access", editor: "edit content" } -------------- 6️⃣ `keyof` – Extract Object Keys type UserKeys = keyof User Result: "id" | "name" | "email" -------------- 7️⃣ `typeof` – Infer Types from Variables const user = { id: 1, name: "Abeer" } type UserType = typeof user --------------- 8️⃣ `as const` – Literal Types const status = ["loading", "success", "error"] as const Now TypeScript knows the exact values. ------------- 9️⃣ Generics Reusable type-safe functions. function identity<T>(value: T): T { return value } --------------- 🔟 Union Types type Status = "loading" | "success" | "error" 💡 **Why this matters** Using TypeScript effectively helps: ✔ Prevent runtime bugs ✔ Improve code readability ✔ Build scalable React applications What’s your favourite TypeScript feature ?
To view or add a comment, sign in
-
TypeScript : Part 2 – Loops & Functions! I'm excited to share the next chapter of my TypeScript learning journey. In this part, I dived deep into the core building blocks: Control Flow (Loops) and Type-Safe Functions. Understanding how to automate tasks and write reusable code is a game-changer! Here’s a breakdown of what I covered with examples: 1. Loops Loops help us run the same block of code multiple times. ■ For Loop: Perfect when you know exactly how many times to repeat. Example: for(let num:number=1; num<=target; num++){ console.log("For Prints: "+ num); } ■ While Loop: Best when you want to run as long as a condition is true Example: let num:number=1; while(num <= target){ console.log("While Prints: "+ num); num++; } ■ Do-While Loop: Unique because it guarantees the code runs at least once, even if the condition is false initially. Example: let num:number=1; do{ console.log("Do-While Prints: "+ num); num++; }while(num <= target); 2. Types of Functions in TypeScript ■ Named Function This is the traditional way to write a function. It has a specific name and can be called anywhere in your code Example: function sayHello(name: string): void { console.log("Hello, " + name + "!"); } sayHello("Akhila"); ■ Anonymous Function A function without a name! Usually, we assign it to a variable. It’s great for logic that doesn't need to be reused globally. Example: let square = function (num: number): number { return num * num; } console.log("square of 5: " + square(5)); ■ Arrow Function (Lambda) The modern, shorthand way to write functions using the => syntax. It’s clean, concise, and very popular in modern web development. Example: const add = (x: number, y: number): number => x + y; ■ Void Function A function that does not return a value. We use the void type to tell TypeScript that this function just performs an action (like logging to the console) and finishes. Example: let greet = function (): void { console.log("Welcome to TypeScript!"); } greet(); Ram Shankar Darivemula | Frontlines EduTech (FLM) Key Takeaway: Using types in functions helps catch bugs during development rather than at runtime. It makes the code much more predictable and easier to read! What's Next? Stay tuned for Part 3 of TypeScript, where I'll be exploring Complex types #TypeScript #WebDevelopment #SoftwareEngineering #Programming #JavaScript #WebDev #DotNet
To view or add a comment, sign in
-
🚀 TypeScript Best Practices: The Comma (,) vs. The Semicolon (;) Whether you're a seasoned engineer or just starting your TypeScript journey, small syntax choices can make a huge difference in code readability and maintainability. One of the most common questions for developers transitioning from JavaScript is: "When do I use a comma versus a semicolon?" Here is a quick breakdown to keep your enterprise-grade codebase clean and consistent. 🏗️ The Semicolon (;): Defining the Blueprint When you are defining Interfaces or Type Aliases, you are creating a "set of instructions" or a contract for the compiler, not actual data. Best Practice: Use semicolons to terminate members in a structural definition. Why? Interfaces are conceptually similar to class definitions. The semicolon tells the TypeScript compiler that the definition of that specific property or method is complete, acting as a clear boundary for the engine. TypeScript // ✅ Good: Clear separation of structural definitions interface User { id: number; name: string; email: string; } 💎 The Comma (,): Handling the Data When you move from defining a type to creating an Object Literal, you are working with live data in the JavaScript runtime. Best Practice: Use commas to separate key-value pairs in an object. Why? In JavaScript, an object is essentially a list of data. Commas are the standard delimiter for items in a list, just like in an array. Using a semicolon inside an object literal is a syntax error that will break your build! TypeScript // ✅ Good: Standard JavaScript object notation const activeUser: User = { id: 1, name: "John Doe", email: "dev@example.com", // Trailing commas are great for cleaner Git diffs! }; 💡 Senior Dev Tips for Your Workflow Visual Distinction: While TS technically allows commas in interfaces, sticking to semicolons helps you distinguish "Types" from "Objects" at a glance during rapid code reviews. Watch the Typos: Ensure your implementation strictly follows your interface—watch out for common spelling slips like balance vs balence which can lead to runtime headaches. Accessibility First: Remember that clean code is accessible code—maintaining strict typing and clear syntax supports better documentation for everyone on the team. What's your preference? Do you stick to semicolons for types to keep things "classy," or do you prefer the comma-everywhere approach? Let's discuss in the comments! 👇 #TypeScript #WebDevelopment #CodingBestPractices #FrontendEngineering #CleanCode #JavaScript #SeniorDeveloper
To view or add a comment, sign in
-
The JavaScript era of TypeScript is officially ending 🚨 TypeScript 6.0 just dropped, and it's a massive turning point. It is officially the final release based on the current JavaScript codebase, serving as the ultimate bridge to TypeScript 7.0—which is completely rewritten in Go. Here is why this drastic new era is going to change how we build for the web: ━━━━━━━━━━━━━━━━━━━━━━ 🚀 The Need for Native Speed TypeScript 6.0 prepares your codebase for the upcoming Go-based TS 7.0 compiler. The future promises shared-memory multi-threading and parallel type-checking, completely eliminating the performance bottlenecks of the current Node.js architecture. 🔥 Aggressive, Modern Defaults Microsoft is finally cutting the legacy cord. Out of the box, TypeScript 6.0 now defaults to: • strict: true (The appetite for strict typing has won) • target: es2025 (Evergreen browsers are the standard; ES5 is dead) • module: esnext (ESM is the undisputed king) 🧹 Massive Ecosystem Cleanup Say goodbye to legacy baggage. They are officially deprecating baseUrl, target: es5, amd/umd module resolutions, and moduleResolution: node10. If you aren't using a modern bundler or NodeNext, it's time to adapt. ✨ Next-Gen ECMAScript Features TS 6.0 ships with built-in types for the highly anticipated Temporal API (goodbye date-math headaches!), Map's new getOrInsert (upsert methods), and RegExp.escape. ⚠️ The "Gotchas" & Migration Tips • Silent Breaks: rootDir now defaults strictly to the location of your tsconfig.json, and global types defaults to []. If your builds rely on TS magically inferring your source folders or global types, they will break. • Stability: Use the new --stableTypeOrdering flag. It ensures your declaration emits don't change based on internal processing order—a crucial step for the parallel type-checking coming in v7. • Quick Fix: Need time? You can set "ignoreDeprecations": "6.0" in your config, but note that TS 7.0 will drop them entirely. (Huge shoutout to Daniel Rosenwasser and the Microsoft TS team for making the tough calls to push the ecosystem forward!) ━━━━━━━━━━━━━━━━━━━━━━ The shift to a Go-based compiler is arguably the biggest architectural change in TypeScript's history. Are you ready to say goodbye to the JS compiler and hello to native speeds? Or will the new strict defaults break your CI pipeline this week? 👇 #TypeScript #WebDev #JavaScript #GoLang #SoftwareEngineering #Frontend #DevOps
To view or add a comment, sign in
-
-
𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝟲.𝟬 𝗞𝗲𝘆 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀 𝗳𝗼𝗿 𝟮𝟬𝟮𝟲 TypeScript 6.0 is here. It sets up major changes for TypeScript 7.0. Here is what matters for your code. **Small fix, big help** TypeScript 6.0 now understands method syntax better. Functions that do not use `this` get better type guesses. Your code works consistently now. **Cleaner imports** You can now use `#/` as an import prefix. This matches bundler tools. Write `import utils from "#/utils.js"` instead of `../../../utils.js`. **Predictable output** A new flag `--stableTypeOrdering` makes union types appear in a fixed order. Your build files will not change randomly. Note: this can slow compilation. **Modern dates** The Temporal API is now built-in. It fixes many problems with JavaScript's Date object. Use it for time zones and durations. **Easier Map updates** Maps have two new methods: - `getOrInsert(key, default)` sets a value if missing. - `getOrInsertComputed(key, function)` runs a function only if the key is missing. **Safer regex** Use `RegExp.escape(userInput)` to safely turn user text into a pattern. You avoid injection bugs. **Breaking changes** New defaults in `tsconfig.json`: - `strict: true` - `module: esnext` - `target: es2025` (floating) - `types: []` (empty, add needed types yourself) You must now list required types explicitly. Options like `baseUrl` are deprecated. Use full paths in `paths` instead. **Your action plan** Immediate: - Update your `tsconfig.json` - Add needed types to the `types` array - Set `rootDir` if your source folder is not the project root Medium term: - Move off `target: es5` - Change module resolution to `nodenext` or `bundler` - Stop using AMD or UMD modules Long term: - Test the `--stableTypeOrdering` flag - Plan for parallel builds in CI when TypeScript 7.0 arrives These changes prepare your project for faster builds. The default settings cut startup time. Source: https://lnkd.in/gu9jP4tb Which feature will you try first? Share your migration steps below.
To view or add a comment, sign in
-
Zod is the best thing to happen to TypeScript APIs since TypeScript itself. I spent 3 years writing manual validation logic in Node.js APIs. Checking if req.body.email is a string. Checking if it's actually an email. Checking if req.body.age is a number and not negative. Writing the error message manually. Remembering to do this on every route. Then I found Zod. I genuinely don't know how I shipped APIs without it. WHAT ZOD DOES Zod lets you define a schema once. That schema does three things: 1. Validates the data at runtime 2. Infers the TypeScript type automatically 3. Produces clean, structured error messages // One schema. Three things at once. import { z } from 'zod' const CreateOrderSchema = z.object({ userId: z.string().uuid(), items: z.array(z.object({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(100) })).min(1, 'Order must have at least one item'), deliveryDate: z.string().datetime().optional(), promoCode: z.string().toUpperCase().optional() }) // TypeScript type — inferred automatically, no duplication type CreateOrder = z.infer USING IT IN AN EXPRESS / NESTJS API const result = CreateOrderSchema.safeParse(req.body) if (!result.success) { return res.status(422).json({ errors: result.error.flatten().fieldErrors }) // Returns exactly which field failed and why // { items: ['Order must have at least one item'] } } // result.data is now fully typed — no casting, no assertions const order = await orderService.create(result.data) 3 ZOD PATTERNS I USE ON EVERY PROJECT 1. .transform() — sanitise on parse, not separately z.string().trim().toLowerCase().email() 2. .refine() — custom logic type-safety can't express z.string().refine(s => isValidIBAN(s), 'Invalid IBAN') 3. Shared schemas between frontend and backend One package, one source of truth, zero API contract drift Zod replaced about 400 lines of manual validation in the last codebase I cleaned up. 400 lines that were inconsistent, untested, and spread across 30 files. One Zod schema file. Consistent everywhere. #TypeScript #NodeJS #WebDevelopment #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
💥 3 years ago I was shipping React + TypeScript code that looked clean. It compiled. Linted. Passed review. And still blew up in production. The problem wasn't my logic. It was the gaps TypeScript was silently allowing. 👇 ━━━━━━━━━━━━━━━━━━ I learned 6 utility types that closed those gaps overnight. ───────────────── 1️⃣ Partial<T> ───────────────── When you need to update only some fields of an object. Before: Passing full user objects to update functions. Missing fields → silent overwrites → corrupted state. After: updateUser(patch: Partial<User>) Now only the fields you pass get touched. The rest? Untouched. Safe. Intentional. ───────────────── 2️⃣ Required<T> ───────────────── The opposite — force every optional field to be present. Perfect for form submission handlers where every field must exist before you hit the API. No more "why is email undefined?" in your POST body. ───────────────── 3️⃣ Pick<T, K> ───────────────── Expose only the fields a component actually needs. Before: Passing the entire User object to a ProfileCard. Result: Components reading fields they shouldn't. Tight coupling. After: type CardProps = Pick<User, 'name' | 'avatar' | 'role'> Your component now knows nothing it doesn't need to know. ───────────────── 4️⃣ Omit<T, K> ───────────────── The inverse — strip fields you never want exposed. type PublicUser = Omit<User, 'passwordHash' | 'internalId'> I use this on every API response type. Sensitive fields can't leak if the type doesn't include them. ───────────────── 5️⃣ Record<K, V> ───────────────── Type-safe dictionaries. Full stop. Before: { [key: string]: any } That "any" is a bug waiting to happen. After: Record<UserId, SessionData> Now both the key and value are typed. Wrong key shape? TypeScript catches it at compile time. ───────────────── 6️⃣ NonNullable<T> ───────────────── Strip null and undefined from a type explicitly. type SafeId = NonNullable<User['id']> Use this before any operation that cannot handle null. You stop writing defensive if-checks everywhere and start making nullability impossible by design. ━━━━━━━━━━━━━━━━━━ The shift these 6 types created wasn't just fewer bugs. It was fewer conversations. Fewer "why is this undefined?" Slack messages at 11pm. Fewer post-mortems for issues that should never compile. TypeScript's power isn't in catching errors at runtime. It's in making entire categories of errors impossible to write. 🔒 ━━━━━━━━━━━━━━━━━━ Which of these are you already using? And which one do you wish you'd learned earlier? Drop it below. ♻️ Repost for every React dev still writing { [key: string]: any } in their codebase. #TypeScript #React #FrontendEngineering #WebDevelopment #JavaScript #SoftwareEngineering #Programming #ReactJS #TechLeadership #100DaysOfCode #CodeQuality #CleanCode #DevOps #OpenSource #Tech
To view or add a comment, sign in
-
Angular is a modern, TypeScript-based framework developed by Google for building dynamic, scalable single-page applications (SPAs). To get started, you’ll need Node.js, Angular CLI, and a basic understanding of HTML, CSS, and JavaScript. 🔑 Key Angular Concepts Component-Based Architecture: Applications are built using reusable components that manage their own logic, templates, and styles. Two-Way Data Binding: Synchronizes data between the model (TypeScript code) and the view (HTML template). Dependency Injection (DI): Provides services and resources efficiently across components. Routing: Enables navigation between different views without reloading the page. Directives: Special markers in templates that extend HTML (e.g., *ngIf, *ngFor). Services: Classes that handle business logic and data, often injected into components. Modules: Group related components, directives, and services together for better organization. ⚙️ Setting Up Angular Install Node.js & npm Download from nodejs.org. Verify installation: bash node -v npm -v Install Angular CLI bash npm install -g @angular/cli Create a New Project bash ng new my-app cd my-app ng serve Open http://localhost:4200 in your browser. 📂 Basic Project Structure src/app/app.component.ts → Main component logic src/app/app.component.html → Template (UI) src/app/app.component.css → Styles app.module.ts → Root module that declares components and imports Angular features 🖥️ Example: Hello World Component typescript import { Component } from '@angular/core'; @Component({ selector: 'app-hello', template: `<h1>Hello Angular!</h1>`, styles: [`h1 { color: blue; }`] }) export class HelloComponent {} Add <app-hello></app-hello> in app.component.html to render it. ⚠️ Common Pitfalls Skipping TypeScript basics → Angular heavily relies on TypeScript. Not modularizing code → Leads to messy projects. Ignoring RxJS → Reactive programming is central to Angular’s data handling. ##Angular
To view or add a comment, sign in
-
📌 Topic: TypeScript Generics — the feature that makes your code truly reusable Most devs use TypeScript to add types. Few use it to write code that is flexible AND fully type-safe at the same time. That's exactly what Generics give you. Without Generics, you end up doing this: 🚫 Any kills all type safety function getFirstItem(arr: any[]): any { return arr[0]; } const num = getFirstItem([1, 2, 3]); // type: any ❌ const str = getFirstItem(['a', 'b']); // type: any ❌ With Generics: ✅ Type flows through — no any, no casting function getFirstItem<T>(arr: T[]): T { return arr[0]; } const num = getFirstItem([1, 2, 3]); // type: number ✅ const str = getFirstItem(['a', 'b']); // type: string ✅ Real-world usage — Generic API response wrapper: interface ApiResponse<T> { data: T; status: number; message: string; } // Reuse across your entire app type UserResponse = ApiResponse<User>; type ProductResponse = ApiResponse<Product>; type OrderResponse = ApiResponse<Order[]>; One interface. Infinite reuse. Zero repetition. Constrained Generics — when T shouldn't be just anything: T must have an 'id' property function findById<T extends { id: number }>(items: T[], id: number): T | undefined { return items.find(item => item.id === id); } findById(users, 1); // ✅ works — User has id findById(products, 5); // ✅ works — Product has id findById([1, 2, 3], 1); // ❌ compile error — number has no id Generic utility types TypeScript ships out of the box: Partial<T> → makes all properties optional Required<T> → makes all properties required Readonly<T> → prevents mutation Pick<T, K> → extract only the keys you need Omit<T, K> → exclude keys you don't want Record<K, V> → build key-value map types The difference between a codebase with Generics and one without is simple: Without Generics → duplicate types everywhere, any sprinkled around, runtime errors TypeScript should have caught With Generics → one source of truth, full type safety, errors caught at compile time not in production If you're writing TypeScript without Generics — you're using 40% of the language. 💡 Which utility type do you reach for the most? 👇 #TypeScript #JavaScript #FullStackDev #WebDevelopment #SoftwareEngineering #Angular #React #CleanCode
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