How to calculate the area, diameter, and circumference of a circle in TypeScript

2 Answers

0 votes
const radius: number = 3;
const PI: number = Math.PI;
     
const area: number = PI * radius * radius;
console.log("Area = " +  area.toFixed(2));
     
const diameter: number = 2 * radius;
console.log("Diameter = " +  diameter.toFixed(2));
     
const circumference: number = 2 * PI * radius;
console.log("Circumference = " +  circumference.toFixed(2));
  
      
      
/*
run:
        
Area = 28.27
Diameter = 6.00
Circumference = 18.85
        
*/

 



answered Aug 29, 2024 by avibootz
edited 3 hours ago by avibootz
0 votes
/**
 * Interface representing the calculated geometric metrics of a circle.
 * Properties are marked as readonly to ensure immutability.
 */
interface CircleMetrics {
    readonly diameter: number;
    readonly circumference: number;
    readonly area: number;
}
 
/**
 * Calculates the diameter, circumference, and area of a circle.
 * 
 * @param radius - The radius of the circle (must be a non-negative number).
 * @returns An object conforming to CircleMetrics containing the calculated results.
 * @throws {TypeError} If the radius is not a valid number.
 * @throws {RangeError} If the radius is negative.
 */
function calculateCircleMetrics(radius: number): CircleMetrics {
    // Validate input type
    if (typeof radius !== 'number' || Number.isNaN(radius)) {
        throw new TypeError('Radius must be a valid number.');
    }
 
    // Guard clause: radius cannot be negative
    if (radius < 0) {
        throw new RangeError('Radius cannot be negative.');
    }
 
    const diameter: number = 2.0 * radius;
    const circumference: number = 2.0 * Math.PI * radius;
     
    // Standard multiplication (radius * radius) is more efficient than Math.pow(radius, 2)
    const area: number = Math.PI * (radius * radius);
 
    return {
        diameter,
        circumference,
        area
    };
}
 
// --- Example Usage ---
try {
    const radius: number = 3.0;
     
    // Retrieve calculated metrics with explicit type annotations
    const metrics: CircleMetrics = calculateCircleMetrics(radius);
 
    // Output results formatted to 2 decimal places using toFixed()
    console.log(`Radius: ${radius}`);
    console.log(`Diameter: ${metrics.diameter}`);
    console.log(`Circumference: ${metrics.circumference.toFixed(2)}`);
    console.log(`Area: ${metrics.area.toFixed(2)}`);
} 
catch (error: unknown) {
    // Type-safe error handling in TypeScript
    if (error instanceof Error) {
        console.error(`Error: ${error.message}`);
    } else {
        console.error('An unexpected error occurred.');
    }
}
 
 
/*
run:
 
Radius: 3
Diameter: 6
Circumference: 18.85
Area: 28.27
 
*/

 



answered 3 hours ago by avibootz

Related questions

...