Unions and Narrowing 28 exercises
Problem

Destructuring a Discriminated Union in TypeScript

Let's continue on with the calculateArea function we developed in our previous exercise.

The function takes a Shape that is either a circle or a square, in the form of a discriminated union.

type Circle = {
  kind: "circle";
  radius: number;
};

type Square = {
  kind: "square";
  sid
Loading exercise

Transcript

00:00 We're starting from the solution for our previous exercise, this CalculateArea function which takes in a circle or a square in the shape of a shape, in the shape of a shape, a discriminated union. And except that we've changed something about it. Instead of it being just shape here,

00:17 we've really inside the function parameters, we've instead changed it to be this structured kind of like object here with kind, radius, and side length destructured from the object. Now we're doing our usual checks here, we're saying if kind is circle, but we're getting some errors. And we're getting an error saying property radius does not exist on type shape.

00:38 Your job is to try to work out why on earth that error is happening and how we can get this destructuring behavior without compromising any of our code and still making all the tests pass below. Good luck.