DEV Community

Ali Hamza
Ali Hamza

Posted on

Day 175 of Learning MERN Stack

Hello Dev Community! 👋

It is officially Day 175 of my full-stack engineering track! Today, I explored one of the most essential features for writing safe dynamic code in TypeScript: Type Narrowing & Type Guards! 📘⚡

Type narrowing allows TypeScript to deduce specific types within conditional code blocks, eliminating type ambiguity and runtime crashes.


🛠️ Technical Breakdown: Type Narrowing Techniques

As captured in my code editor setup (index.ts):

1. Discriminated Unions (Tagged Unions)

  • Utilized a common literal discriminator property (type) across distinct object types to cleanly handle polymorphic structures via switch statements:

typescript
  type MasalaChai = { type: 'Masala', spicelevel: number };
  type GingerChai = { type: 'Ginger', amount: number };
  type ElaichiChai = { type: 'Elaichi', packet: number };

  type Chai = MasalaChai | GingerChai | ElaichiChai;

  const makeChai = (order: Chai) => {
    switch (order.type) {
      case 'Elaichi': return "Elaichi Wali Chai";
      case 'Ginger': return "Ginger Wali Chai";
      case 'Masala': return "Masala Wali Chai";
    }
  };
Enter fullscreen mode Exit fullscreen mode

Top comments (0)