Complete the code to define a discriminated union type for shapes.
type Shape = Circle | Square;
interface Circle {
kind: [1];
radius: number;
}The kind property is used as the discriminant with the value "circle" to identify the Circle type.
Complete the code to add a Square type to the discriminated union.
interface Square {
kind: [1];
sideLength: number;
}The kind property for Square should be the string literal "square" to distinguish it from other shapes.
Fix the error in the function to correctly narrow the shape type using the discriminated union.
function area(shape: Shape): number {
if (shape.kind === [1]) {
return Math.PI * shape.radius ** 2;
} else {
return shape.sideLength * shape.sideLength;
}
}The discriminant check should compare shape.kind to "circle" to narrow the type to Circle.
Fill both blanks to create a discriminated union and a function that returns the perimeter.
type Shape = [1] | [2]; function perimeter(shape: Shape): number { switch (shape.kind) { case "circle": return 2 * Math.PI * shape.radius; case "square": return 4 * shape.sideLength; } }
The discriminated union Shape is made of Circle and Square types.
Fill all three blanks to define a discriminated union with a Triangle type and extend the area function.
interface Triangle {
kind: [1];
base: number;
height: number;
}
type Shape = Circle | Square | [2];
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength * shape.sideLength;
case [3]:
return 0.5 * shape.base * shape.height;
}
}The Triangle interface uses the discriminant "triangle". The union includes Triangle, and the switch case uses the string "triangle" to calculate the area.