Building a Simple TypeScript Calculator
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: Define the 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;
}
These functions perform basic arithmetic operations.
Step 2: 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 class encapsulates the calculator functions.
Step 3: 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 it to perform calculations.
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.