0
0
Typescriptprogramming~15 mins

Discriminated union narrowing in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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 Rectangle
Each variant must have a kind property with a unique string literal
Add properties specific to each shape: radius for circle, width and height for rectangle
Write a function getArea that takes a Shape and returns its area using discriminated union narrowing
Use 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
1
Create the Shape union type
Create a type called Shape that is a union of two object types: one with kind set to "circle" and a radius number property, and another with kind set to "rectangle" and width and height number properties.
Typescript
Need a hint?

Use a union type with | and include the kind property with string literals.

2
Create a sample shape variable
Create a constant called myShape and assign it an object with kind set to "circle" and radius set to 5.
Typescript
Need a hint?

Assign an object matching the circle variant of Shape.

3
Write the getArea function with discriminated union narrowing
Write a function called getArea that takes a parameter shape of type Shape. Use a switch statement on shape.kind to return the area: for "circle", return Math.PI * shape.radius ** 2; for "rectangle", return shape.width * shape.height.
Typescript
Need a hint?

Use a switch on shape.kind to narrow the type and calculate the area accordingly.

4
Print the area of myShape
Write a console.log statement that prints the result of calling getArea with myShape.
Typescript
Need a hint?

Call getArea(myShape) and print the result with console.log.