TypeScript Tutorial
TypeScript Project: Calculator
A four-function calculator with functions per operator and a check for divide-by-zero.
What you will build
This project is a four-function calculator: add, subtract, multiply, and divide. Each operator lives in its own function so the arithmetic is not copied into every branch. Division checks the divisor before it runs. A zero divisor prints a message instead of crashing or printing infinity.
The examples use hardcoded numbers so they compile and print at once. Click Try it in TypeScriptto open /typescript/try. That editor is tsc in the browser. After the logic is clear, you can replace the literals withreadLine().
One function per operator
A function has a name, typed parameters, and a return type. TypeScript runs the file from the top; there is nomain. Each operator takes two number values and returns a number. Usingnumber keeps 10 divided by 4 as 2.5, not 2.
Example
function add(a: number, b: number): number {
return a + b;
}
function subtract(a: number, b: number): number {
return a - b;
}
console.log(add(10, 4));
console.log(subtract(10, 4));Output is 14 then 6. Change 10 to 3.5 and compile again. The function bodies stay the same; only the arguments change.
Multiply and a named result
Store the return value when you need it more than once, or when you want a name that documents the meaning.product is easier to read in a print line than a nested call.
Example
function multiply(a: number, b: number): number {
return a * b;
}
const product: number = multiply(10, 4);
console.log("10 * 4 = " + product);Use Try it in TypeScript under the example so the program opens at/typescript/try. The Python editor at /try will not type-check this file.
Guard divide-by-zero
Division by zero is not a useful result for a calculator. Check the divisor first. This version returnsnumber | null: the quotient when the division is safe, and null when the divisor is zero. The caller then decides what to print.
Example
function divide(a: number, b: number): number | null {
if (b === 0) {
return null;
}
return a / b;
}
const q1: number | null = divide(10, 4);
if (q1 !== null) {
console.log("10 / 4 = " + q1);
} else {
console.log("Cannot divide by zero");
}
const q2: number | null = divide(10, 0);
if (q2 !== null) {
console.log("10 / 0 = " + q2);
} else {
console.log("Cannot divide by zero");
}The first call prints 10 / 4 = 2.5. The second call prints the error line. After a failed divide, there is no leftover quotient to print by accident: the value is null.
Complete calculator
Pick an operator with a string and an if / else if chain. Call the matching function. Unknown operators get their own message. This program runs six hardcoded cases so you can see every branch without typing.
Example
function add(a: number, b: number): number {
return a + b;
}
function subtract(a: number, b: number): number {
return a - b;
}
function multiply(a: number, b: number): number {
return a * b;
}
function divide(a: number, b: number): number | null {
if (b === 0) {
return null;
}
return a / b;
}
function calculate(a: number, op: string, b: number): void {
const prefix: string = a + " " + op + " " + b + " = ";
if (op === "+") {
console.log(prefix + add(a, b));
} else if (op === "-") {
console.log(prefix + subtract(a, b));
} else if (op === "*") {
console.log(prefix + multiply(a, b));
} else if (op === "/") {
const q: number | null = divide(a, b);
if (q !== null) {
console.log(prefix + q);
} else {
console.log(prefix + "Cannot divide by zero");
}
} else {
console.log(prefix + "Unknown operator");
}
}
calculate(10, "+", 4);
calculate(10, "-", 4);
calculate(10, "*", 4);
calculate(10, "/", 4);
calculate(10, "/", 0);
calculate(10, "%", 4);The last line is not remainder. This calculator does not implement %, so that case printsUnknown operator. Keep the operator set small until the four functions are solid.
Later, typed input can replace the hardcoded calls with Number(readLine()) and a loop. Leave that until the functions and the zero check already work.
Common mistakes
- Comparing the divisor with
==only when you meant===. For a literal zero both work, but stick to===so a string"0"does not slip through. - Checking the divisor after the division. The test must run first. An
ifaftera / bis too late. - Comparing operators with a one-character type that TypeScript does not have.
opis astring. Write"/", not a C++-style'/'if you want a string match. - Returning
undefinedfrom divide without a union type. Annotatenumber | nullso the caller is forced to handle the failure.
Practice
- Change the first operand from 10 to 3.5 and compile again. Confirm add, subtract, multiply, and divide all update.
- Add a power function that returns
araised to an integer exponent using a loop, notMath.pow. - Print each successful result with two digits after the decimal using
toFixed(2).
Next project: a roster of students in a typed array, with a printed list and a top score.