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 viaswitchstatements:
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";
}
};
Top comments (0)