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 if aftera / b is too late.
  • Comparing operators with a one-character type that TypeScript does not have. op is astring. Write "/", not a C++-style '/' if you want a string match.
  • Returning undefined from divide without a union type. Annotatenumber | null so the caller is forced to handle the failure.

Practice

  1. Change the first operand from 10 to 3.5 and compile again. Confirm add, subtract, multiply, and divide all update.
  2. Add a power function that returns a raised to an integer exponent using a loop, not Math.pow.
  3. 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.

FAQ: TypeScript Project: Calculator

Common questions about this page.

What is the StudyGrid TypeScript tutorial?

The StudyGrid TypeScript tutorial follows the same chapter rhythm as C++: syntax, types, input, loops, functions, classes, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run typescript calculator project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn typescript calculator project in this TypeScript TypeScript lesson (TypeScript Project: Calculator).

Is the TypeScript editor the same as Try Python or Try C++?

No. Try TypeScript type-checks with tsc at /typescript/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. TypeScript lessons never open those editors.

Do I need to install a compiler to learn TypeScript?

No. Open a chapter, click Try it in TypeScript, and compile in the browser. You can also download a .ts file and compile locally with tsc.

Where should I start the TypeScript tutorial?

Start at TypeScript Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open TypeScript Examples, then generics, Map, and arrow functions. Use Next at the bottom of each chapter.

Is the TypeScript tutorial free?

Yes. The TypeScript workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.