Discriminated Union Narrowing in TypeScript
📖 Scenario: You are building a simple program that handles different shapes. Each shape has a type and specific properties. You want to write code that safely works with each shape type.
🎯 Goal: Create a discriminated union of shapes and write code that narrows the type based on the kind property to calculate the area.
📋 What You'll Learn
Create a union type called
Shape with two variants: Circle and RectangleEach variant must have a
kind property with a unique string literalAdd properties specific to each shape:
radius for circle, width and height for rectangleWrite a function
getArea that takes a Shape and returns its area using discriminated union narrowingUse a
switch statement on the kind property inside getArea💡 Why This Matters
🌍 Real World
Discriminated unions are useful when working with data that can be one of several types, like different shapes, events, or messages.
💼 Career
Understanding discriminated union narrowing is important for writing safe and clear TypeScript code in frontend and backend development.
Progress0 / 4 steps