Sequence NODE_176
MediumWrite a Function to Compute Shape Area
TypeScript
Technical Specification
Using the Shape type, implement a function that returns the area of either a circle or a rectangle.
Input/Output Samples
Input:{ kind: "circle", radius: 2 }
Output:12.566...
Optimal Logic Path
function area(shape: { kind: "circle"; radius: number } | { kind: "rectangle"; width: number; height: number }) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius * shape.radius;
case "rectangle":
return shape.width * shape.height;
}
}Architectural Deep-Dive
Control flow narrowing lets TypeScript infer the correct shape type inside each switch case.