Complete the code to match the shape type using a switch statement.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius * shape.radius;
case [1]:
return shape.size * shape.size;
}
}Complete the code to add a default case that throws an error for unknown shapes.
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius * shape.radius;
case 'square':
return shape.size * shape.size;
default:
throw new Error([1]);
}
}Fix the error in the exhaustive check by adding a never type assertion.
function assertNever(x: never): never {
throw new Error('Unexpected object: ' + x);
}
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius * shape.radius;
case 'square':
return shape.size * shape.size;
default:
return [1];
}
}Fill both blanks to create an exhaustive switch that returns the perimeter of the shape.
function perimeter(shape: Shape): number {
switch (shape.kind) {
case [1]:
return 2 * Math.PI * shape.radius;
case [2]:
return 4 * shape.size;
}
}Fill all three blanks to create an exhaustive pattern match with a never check.
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case [1]:
return Math.PI * shape.radius * shape.radius;
case [2]:
return shape.size * shape.size;
case [3]:
return shape.width * shape.height;
default:
return assertNever(shape);
}
}