Discriminated Unions in TypeScript
π Scenario: You are building a simple system to handle different shapes in a drawing app. Each shape has a type and specific properties. You want to write code that can safely work with these shapes by checking their type.
π― Goal: Create a TypeScript program that uses discriminated unions to define different shapes, then write code to calculate the area of each shape based on its type.
π What You'll Learn
Define a union type called
Shape with discriminated property kindInclude three shapes:
circle, rectangle, and triangleWrite a function
calculateArea that takes a Shape and returns its areaUse a
switch statement on shape.kind to handle each shape typePrint the area for each shape in a list
π‘ Why This Matters
π Real World
Discriminated unions help safely handle different data types in one variable, common in apps that process varied inputs like shapes, events, or messages.
πΌ Career
Understanding discriminated unions is important for TypeScript developers to write clear, type-safe code that prevents bugs and improves maintainability.
Progress0 / 4 steps