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 theShapetype and theShapeKindtype.calculations.ts: Implement the shape calculation functions and export theShapeCalculatortype,calculateAreafunction, andcalculateCircumferencefunction.report.ts: Create thecreateShapeReportfunction 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, andTrianglefor each specific shape. Each shape interface should have akindproperty of a discriminated union type. Export these interfaces. - Define the
Shapetype as a union type ofCircle,Rectangle, andTriangle. - Define the
ShapeKindtype as the mapped type that extracts thekindproperty values from theShapetype.
- Import the
Shapetype fromshapes.ts. - Define the
ShapeCalculatortype as a function type that accepts a shape of typeShapeand returns a number. - Implement the
calculateAreafunction that calculates the area based on the shape type using a switch statement. Export this function. - Implement the
calculateCircumferencefunction that calculates the circumference based on the shape type using a switch statement. Export this function.
- Import the
ShapeandShapeKindtypes fromshapes.ts, and theShapeCalculatortype fromcalculations.ts. - Implement the
createShapeReportfunction that takes an array of shapes and a shape calculator function. Iterate through the shapes using afor...ofloop and generate an array of shape reports. Each shape report should have akindproperty of typeShapeKindand avalueproperty 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
createShapeReportfunction withcalculateAreato generate a shape report for the areas of the shapes. Iterate through the resulting array using afor...ofloop and log each shape's kind and calculated area to the console. - Use the
createShapeReportfunction withcalculateCircumferenceto generate a shape report for the circumferences of the shapes. Iterate through the resulting array using afor...ofloop and log each shape's kind and calculated circumference