Complete the code to check the shape type using discriminated union.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function area(shape: Shape) {
if (shape.kind === [1]) {
return Math.PI * shape.radius ** 2;
}
return shape.size * shape.size;
}Complete the code to narrow the union using a switch statement.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function perimeter(shape: Shape) {
switch (shape.kind) {
case [1]:
return 2 * Math.PI * shape.radius;
case 'square':
return 4 * shape.size;
}
}Fix the error in the type narrowing to access the correct property.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function describe(shape: Shape) {
if (shape.kind === 'square') {
return `Square with size ${shape.[1]`;
} else {
return `Circle with radius ${shape.radius}`;
}
}Fill both blanks to correctly narrow the union and access properties.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function getInfo(shape: Shape) {
if (shape.[1] === [2]) {
return shape.radius;
}
return shape.size;
}Fill all three blanks to create a function that returns the area using discriminated union narrowing.
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };
function calculateArea(shape: Shape) {
return {
[1]: (shape.kind === [3] ? shape.[2] : shape.size),
area: shape.kind === [3] ? Math.PI * shape.radius ** 2 : shape.size ** 2
};
}