Why TypeScript? Catching Bugs Early

Why TypeScript? Catching Bugs Early in JavaScript: Imagine you are building a bridge. Vanilla JS: You start building and hope the pieces fit together.

Concept Explanation

Imagine you are building a bridge.

  • Vanilla JS: You start building and hope the pieces fit together. If they don't, the bridge collapses when a car drives over it.
  • TypeScript: The pieces are color-coded and have unique shapes. If you try to put a round pipe into a square hole, the computer stops you before you even start building.

TypeScript is a Static Type Checker. It ensures that if a function expects a number, you don't accidentally pass it a string.


Technical Concept: The Compilation Step

Browsers don't understand TypeScript. You write .ts files, and a tool (the TypeScript Compiler or Vite) "Strips away" the type information to create a normal .js file. The safety happens while you are typing, not while the app is running.


Best Practices

  • Avoid 'any': Using any is like telling the security guard to go home. It makes TypeScript useless. Use unknown if you really don't know the type.
  • Strict Mode: Always keep strict: true in your tsconfig.json. It forces you to handle null and undefined cases.
  • Infer when possible: You don't need to type everything. If you write let x = 5, TypeScript already knows x is a number. Don't clutter the code!

Practice Exercises

  1. The Fixer: Take a JS function that crashes when passed a string: function double(n) { return n * 2 }. Rewrite it in TS so it only accepts numbers.
  2. The 'any' Hunt: Research why the community says "any is a contagious disease." Explain how it spreads through your codebase.
  3. The Compiler: Run npx tsc --init in a folder and look at the tsconfig.json. Find the target setting and explain what it does.