beginner#TypeScript#Calculator#Functions
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.