In this exercise, you will practice:
- Interfaces
- Union Types
- Functional programming
- Typescript project structure
Implement a shape calculation and reporting system. The app will calculate the area and circumference of different shapes, including circles, rectangles, and triangles. You will then generate a shape report based on the calculated values.
shapes.ts
: Define the interfaces for specific shapes and export theShape
type and theShapeKind
type.calculations.ts
: Implement the shape calculation functions and export theShapeCalculator
type,calculateArea
function, andcalculateCircumference
function.report.ts
: Create thecreateShapeReport
function that generates a shape report and export it.index.ts
: Use the implemented functions to calculate the area and circumference of shapes and generate the shape report.
- Define the interfaces
Circle
,Rectangle
, andTriangle
for each specific shape. Each shape interface should have akind
property of a discriminated union type. Export these interfaces. - Define the
Shape
type as a union type ofCircle
,Rectangle
, andTriangle
. - Define the
ShapeKind
type as the mapped type that extracts thekind
property values from theShape
type.
- Import the
Shape
type fromshapes.ts
. - Define the
ShapeCalculator
type as a function type that accepts a shape of typeShape
and returns a number. - Implement the
calculateArea
function that calculates the area based on the shape type using a switch statement. Export this function. - Implement the
calculateCircumference
function that calculates the circumference based on the shape type using a switch statement. Export this function.
- Import the
Shape
andShapeKind
types fromshapes.ts
, and theShapeCalculator
type fromcalculations.ts
. - Implement the
createShapeReport
function that takes an array of shapes and a shape calculator function. Iterate through the shapes using afor...of
loop and generate an array of shape reports. Each shape report should have akind
property of typeShapeKind
and avalue
property of typestring
, which represents the calculated value. Export this function.
- Import the necessary types and functions from
shapes.ts
,calculations.ts
, andreport.ts
. - Create instances of different shapes (e.g., circle, rectangle, triangle).
- Create an array of shapes containing the instances created in the previous step.
- Use the
createShapeReport
function withcalculateArea
to generate a shape report for the areas of the shapes. Iterate through the resulting array using afor...of
loop and log each shape's kind and calculated area to the console. - Use the
createShapeReport
function withcalculateCircumference
to generate a shape report for the circumferences of the shapes. Iterate through the resulting array using afor...of
loop and log each shape's kind and calculated circumference