Open this lesson on a wider screen to play it. The narrated transcript and animated code need room to sit side by side.
← All lessons// Plain TypeScript: switch on a discriminant. With no exhaustiveness guard, add a
// "Triangle" variant later and this still compiles — the return type just quietly
// widens to include undefined, and the missing case ships.
type Shape =
| { _tag: "Circle"; radius: number }
| { _tag: "Square"; side: number };
const area = (shape: Shape) => {
switch (shape._tag) {
case "Circle":
return Math.PI * shape.radius ** 2;
case "Square":
return shape.side ** 2;
}
};
// ^? (shape: Shape) => number
console.log(area({ _tag: "Square", side: 3 })); // 9