BeginnerCoder
beginner#TypeScript#Calculator#Functions

Building a Simple TypeScript Calculator

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Create a basic calculator using TypeScript and learn about functions and variables.

Calculator Project

In this tutorial, we will build a simple calculator using TypeScript.

Step 1: Create a New TypeScript Project

Create a new folder for your project and navigate to it in your terminal. Then, run the following command to create a new TypeScript project:

tsc --init

Step 2: Define Calculator Functions

Create a new file called calculator.ts and add the following code:

function add(x: number, y: number): number {
  return x + y;
}
function subtract(x: number, y: number): number {
  return x - y;
}
function multiply(x: number, y: number): number {
  return x * y;
}
function divide(x: number, y: number): number {
  if (y === 0) {
    throw new Error('Cannot divide by zero');
  }
  return x / y;
}

This code defines four functions for basic arithmetic operations.

Step 3: Create a Calculator Class

Add the following code to the calculator.ts file:

class Calculator {
  add(x: number, y: number): number {
    return x + y;
  }
  subtract(x: number, y: number): number {
    return x - y;
  }
  multiply(x: number, y: number): number {
    return x * y;
  }
  divide(x: number, y: number): number {
    if (y === 0) {
      throw new Error('Cannot divide by zero');
    }
    return x / y;
  }
}

This code defines a Calculator class with methods for basic arithmetic operations.

Step 4: Use the Calculator

Create a new file called main.ts and add the following code:

const calculator = new Calculator();
console.log(calculator.add(2, 3));
console.log(calculator.subtract(5, 2));
console.log(calculator.multiply(4, 5));
console.log(calculator.divide(10, 2));

This code creates a new Calculator object and uses its methods to perform arithmetic operations.

Keep going with TypeScript

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.