Skip to Content
Course content

1: Why TypeScript: Static Typing Benefits

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was tasked with fixing a critical bug in a legacy JavaScript checkout system. The app was crashing for a small percentage of users during the final payment step. After digging through logs for two hours, I found the culprit: a function expecting a discountCode object, but in one specific edge case, the API was returning null. JavaScript didn't care when the function was called; it just happily passed that null along until it tried to access discountCode.percentage. Then, boom—TypeError: Cannot read property 'percentage' of null—and the user's browser froze.

I spent the rest of the afternoon adding "defensive" if-statements everywhere. if (discountCode && discountCode.percentage) { ... }. It felt like I was writing more code to protect against the language than I was writing to actually build the feature. That's the exact moment I realized that relying on runtime checks is like trying to find a leak in a pipe by waiting for your basement to flood. I needed a way to find the leak before the water even started flowing.

Stopping the Runtime Roulette

In plain JavaScript, variables are dynamic. You can assign a number to a variable and then, three lines later, assign it a string. Most of the time, that's fine. But in a large codebase with five other developers, you can't keep the entire data structure of your application in your head. You start guessing. "I think this function returns an array, but maybe it returns undefined if the search is empty?"

TypeScript replaces that guessing game with static typing. Instead of waiting for the code to crash in the user's browser, TypeScript catches these mismatches while you're still writing the code. If you tell TypeScript that a function requires a User object, it will literally refuse to compile if you try to pass it a string or a null value. It turns a "production outage" into a "red squiggly line in my editor" that takes two seconds to fix.

// JavaScript: You don't know it's broken until you run it
function calculateTotal(price, tax) {
  return price + tax;
}
console.log(calculateTotal(100, "10")); // Result: "10010" (Ouch.)

// TypeScript: The editor warns you immediately
function calculateTotal(price: number, tax: number) {
  return price + tax;
}
calculateTotal(100, "10"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.


Living Documentation That Can't Lie

I've seen a lot of projects with huge README files and Confluence pages explaining how the data models work. The problem is that documentation rots. A developer changes a field name in the database, forgets to update the wiki, and suddenly the documentation is lying to you. I've spent entire days following outdated docs only to find out the API changed six months ago.

With TypeScript, the types are the documentation. When you hover over a function or a variable, your IDE tells you exactly what it is. If you change a property name in an interface, TypeScript will instantly highlight every single place in your entire project where that property was used and tell you it's now broken. You don't have to search and replace and pray; you just follow the errors until the red lines disappear. It gives you the confidence to refactor scary parts of the codebase because you know the compiler has your back.




📋 Practical Task

Fixing the Broken Invoice Calculator

You've inherited a small piece of JavaScript code for an invoice system, but it's causing bugs because the data coming from the API is inconsistent. Your task is to convert this to TypeScript to prevent these errors.

The Goal: Create a Product interface and apply it to the calculateInvoice function so that the compiler prevents non-numeric values from being used in the total.

// Current broken JS code:
function calculateInvoice(items) {
  return items.reduce((acc, item) => {
    return acc + item.price;
  }, 0);
}

const order = [
  { name: "Laptop", price: 1200 },
  { name: "Mouse", price: "25" }, // This string is causing the bug!
];

console.log(calculateInvoice(order)); 

Requirements:

  • Define an interface named Product with name (string) and price (number).
  • Type the items parameter in calculateInvoice as an array of Product.
  • Observe how TypeScript flags the "25" in the order array as an error.
  • Fix the data in the order array to satisfy the type checker.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.