TypeScript Program to Add Two Numbers: A Complete Guide

As a TypeScript developer with over six years of experience, I’ve worked on numerous projects where even the simplest operations, such as adding two numbers, must be implemented correctly.

While adding numbers might seem trivial, understanding the TypeScript approach to doing so opens doors to improved type safety and code quality.

In this article, I’ll guide you through various methods for adding two numbers in TypeScript, ranging from basic implementations to more advanced approaches. So let’s dive in!

Basic Method: Adding Two Numbers in TypeScript

The simplest way to add two numbers in TypeScript is to create a function that takes two number parameters and returns their sum.

function addNumbers(num1: number, num2: number): number {
    return num1 + num2;
}

// Example usage
const sum = addNumbers(5, 7);
console.log(sum); // Output: 12

The type annotations in this function ensure that both inputs are numbers and that the function returns a number. This is one of the key benefits of TypeScript – it catches type errors before runtime.

TypeScript Program to Add Two Numbers

Using Arrow Functions in TypeScript

If you prefer a more concise syntax, you can use an arrow function:

const addNumbers = (num1: number, num2: number): number => num1 + num2;

// Example usage
console.log(addNumbers(10, 20)); // Output: 30

Arrow functions are perfect for simple operations like this and are widely used in modern TypeScript projects.

Use Arrow Function to add two numbers in TypeScript

Handling Different Input Types in TypeScript

In real-world applications, you might receive inputs from various sources, like form fields or API responses. Let’s create a more robust function that can handle different input types:

function addNumbers(num1: number | string, num2: number | string): number {
    // Convert inputs to numbers if they're strings
    const value1 = typeof num1 === 'string' ? parseFloat(num1) : num1;
    const value2 = typeof num2 === 'string' ? parseFloat(num2) : num2;

    // Check if the values are valid numbers
    if (isNaN(value1) || isNaN(value2)) {
        throw new Error('Invalid input: Both inputs must be valid numbers or numeric strings');
    }

    return value1 + value2;
}

// Example usage
console.log(addNumbers(5, '10')); // Output: 15
console.log(addNumbers('7.5', 2.5)); // Output: 10

This function can accept both numbers and numeric strings, making it more flexible for various use cases.

Handling Different Input Types in TypeScript

Creating a Generic Add Function in TypeScript

For more advanced TypeScript usage, you might want to create a generic function that works with different numeric types:

function add<T extends number>(a: T, b: T): T {
    return (a + b) as T;
}

// Example usage
const intSum = add<number>(5, 7);
console.log(intSum); // Output: 12

// Works with floating point numbers too
const floatSum = add<number>(3.14, 2.71);
console.log(floatSum); // Output: 5.85

This generic approach ensures type consistency between inputs and outputs.

Create Generic Add Function in TypeScript

Building a Calculator Class in TypeScript

For a more object-oriented approach, you could create a Calculator class:

class Calculator {
    // Method to add two numbers
    add(num1: number, num2: number): number {
        return num1 + num2;
    }

    // Add more calculator methods as needed
    subtract(num1: number, num2: number): number {
        return num1 - num2;
    }

    multiply(num1: number, num2: number): number {
        return num1 * num2;
    }

    divide(num1: number, num2: number): number {
        if (num2 === 0) {
            throw new Error('Division by zero is not allowed');
        }
        return num1 / num2;
    }
}

// Example usage
const calc = new Calculator();
console.log(calc.add(15, 27)); // Output: 42

This approach is useful when you need to bundle related mathematical operations together.

Building a Calculator Class in TypeScript

Real-World Example in TypeScript: Sales Tax Calculator

Let’s look at a practical example where we might use our number addition function – calculating sales tax for an e-commerce application:

interface Product {
    name: string;
    price: number;
}

function calculateTotalWithTax(product: Product, taxRate: number): number {
    const taxAmount = product.price * (taxRate / 100);
    return addNumbers(product.price, taxAmount);
}

// Our trusted add function
function addNumbers(num1: number, num2: number): number {
    return num1 + num2;
}

// Example usage with New York sales tax (8.875%)
const laptop: Product = {
    name: 'MacBook Pro',
    price: 1299
};

const totalPrice = calculateTotalWithTax(laptop, 8.875);
console.log(`Total price of ${laptop.name} with NY tax: $${totalPrice.toFixed(2)}`);
// Output: Total price of MacBook Pro with NY tax: $1414.39

This example illustrates how our simple addition function can be integrated into a larger, practical application.

Real-World Example to Add Two Numbers in TypeScript

Conclusion

I hope you found this article helpful! While adding two numbers might seem straightforward, implementing it properly in TypeScript with proper typing, error handling, and testing creates robust, maintainable code. As you build more complex applications, these fundamentals become increasingly important.

Whether you’re creating a financial application, a game, or any other project that requires numerical operations, these techniques will help you write cleaner, more type-safe code.

Other TypeScript articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.