beginner#TypeScript#calculator#functions
Building a Simple Calculator with TypeScript
Create a basic calculator using TypeScript and learn about functions, variables, and data types.
Building a Calculator
In this tutorial, we'll build a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.
Step 1: Setting Up the Project
First, create a new TypeScript project by running the following command in your terminal:
npm init -y
Then, install the required dependencies:
npm install typescript --save-dev
Step 2: Creating the Calculator Function
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;
}
Step 3: Using the Calculator Function
To use the calculator function, create a new file called index.ts and add the following code:
import { add, subtract, multiply, divide } from './calculator';
console.log(add(2, 3));
console.log(subtract(5, 2));
console.log(multiply(4, 5));
console.log(divide(10, 2));