TypeScript: Divide Two Numbers

1. Introduction

TypeScript, an extended version of JavaScript, adds static typing which ensures more predictable code behavior. Division, a basic arithmetic operation, can be reliably executed in TypeScript due to its type-checking feature. In this tutorial, you'll learn to create a TypeScript function to divide two numbers, handling edge cases like division by zero.

2. Program Steps

1. Define a function named divide.

2. Use TypeScript's type annotations to ensure type correctness.

3. Check for division by zero within the function.

4. Test the function and print results to the console.

3. Code Program

// 1. Define the function to divide two numbers.
function divide(num1: number, num2: number): number | string {
    // 3. Check if the divisor is zero.
    if (num2 === 0) {
        return 'Error: Division by zero is not allowed.';
    }
    // Return the division result.
    return num1 / num2;
}

// 4. Test the function with sample values.
console.log(`Result of 20 divided by 4: ${divide(20, 4)}`);
console.log(`When trying to divide 20 by 0: ${divide(20, 0)}`);

Output:

Result of 20 divided by 4: 5
When trying to divide 20 by 0: Error: Division by zero is not allowed.

4. Step By Step Explanation

1. First, we declare the function divide using TypeScript. The : number annotations confirm that our parameters are indeed numbers.

2. For the function's return type, we specify number | string. This means the function can return either a numeric result or a string-based error message.

3. Inside our function, we handle the edge case of division by zero. If we try to divide by zero, the function returns an error message.

4. We then proceed to test our function using two number sets: one for a regular division and the other for division by zero. The results are printed out, showcasing both a successful division and the error message for division by zero.

Comments