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));
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based TypeScript video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked TypeScript books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.