Skip to main content

Why use TypeScript?

Have you ever looked at a codebase you are not familiar with and when looking at existing functions you couldn’t tell what type of arguments does it expect or what does it return? TypeScript solves this problem by adding types to JavaScript. Here’s an example of a function in JavaScript:
const calculateTotal = (items, taxRate) => {
  let total = 0;
  for (let item of items) {
    total += item.price * item.quantity;
  }
  return total + total * taxRate;
}
In this JavaScript function, it’s not immediately clear:
  • What structure items should have. We can guess it’s an array of objects with price and quantity properties, but it’s not specified.
  • What type taxRate should be. It seems like it should be a number, but there’s nothing preventing a caller from passing something else, like a string.
  • What the function returns. It seems to return a number (the total cost), but there’s no explicit guarantee.
Now, let’s see how TypeScript can improve this by adding type annotations to the function:
type Item = {
  price: number;
  quantity: number;
}

const calculateTotal = (items: Item[], taxRate: number): number => {
  let total = 0;
  for (let item of items) {
    total += item.price * item.quantity;
  }
  return total + total * taxRate;
}
In this TypeScript version:
  • The items parameter is explicitly an array of Item objects, where Item is a type with price and quantity as numbers. This prevents passing in an array of objects that don’t match the expected structure.
  • The taxRate parameter is explicitly a number, preventing callers from passing a value of another type.
  • The function is explicitly defined to return a number, clarifying the expected output and ensuring the function implementation adheres to this contract.
This makes it clear what the function expects and what it returns, and it also helps catch errors early in the development process by providing immediate feedback when the function is used incorrectly. You can try these in the TypeScript playground here. Try adding a label property to the object that is being passed to the function. You should see TypeScript complaining about the type mismatch as the type Item is not expecting a label property.

Common mistakes and Standards

  1. Don’t use any type unless you really have to. It defeats the purpose of using TypeScript.
  2. Avoid using Interface when you can use Type. Type is more flexible and can be used to define union types, intersection types, and more.
  3. Basic types like string, number, boolean, object, array are lowercase. String, Number, Boolean, Object, Array are classes and should be avoided.