Thuta Learning
TypeScript
BasicProgrammingIntermediate

Why Use TypeScript?

TypeScriptLesson 320 min

What you'll walk away with

  • Show how TypeScript catches a string-versus-number bug before the code runs
  • Explain the three benefits (static checking, autocomplete, maintainability) with one example each
  • Convert data from a form or an API correctly at the boundary (`Number()` versus `as`)
  • Name the kinds of bugs TypeScript does not protect you from

Explain it simply

Why people use TypeScript

In a JavaScript project with five files, you can keep in your head what every function expects. With five hundred files and ten developers, that knowledge no longer fits in anyone's head: the code gets messy and bugs become hard to track down.

TypeScript asks you to write that knowledge into the code itself. The computer then remembers it for you and points at mistakes immediately. The result is three advantages: fewer bugs, smarter suggestions from your editor, and code that is easier to read and change.

Problem → Why → Solution

The problem: "100" + 10 = "10010"

HTML inputs always give you a string, whatever the user typed. Pass a price from a form straight into a tax function and the `*` operator converts the string to a number, but the `+` operator glues two pieces of text together.

The result is `"10010"`, not `110`. Nothing crashes, so the value can travel into an invoice or a database. Often you only find out when a customer complains about a bill for 10,010 dollars.

tax.js
// JavaScript: price is supposed to be a number, but nothing says so
function addTax(price, rate) {
  return price + price * rate;
}

const priceFromForm = "100";            // input.value is always a string
console.log(addTax(priceFromForm, 0.1)); // "10010" instead of 110

Why this bug is so hard to find

There is no error message at all, and the place where the bug starts (reading the form) is far from the place where you see it (the invoice), in another file and at another time. With `price: number`, TypeScript flags the exact call: 'Argument of type string is not assignable to parameter of type number'.

Core concept: three benefits and their limits

The cost of fixing a bug depends on the distance between where it starts and where it is noticed. A red underline while you type costs seconds. A bug a customer finds in production costs hours of digging through logs, repairing data and apologizing. All three of TypeScript's benefits aim to shrink that distance.

Static type checking

It finds type-related errors at compile time, before you run anything: a string ending up in a number variable, reading a property that does not exist, the wrong number of arguments, using a value that might be `undefined` without checking. Tests only check the paths they run; the compiler checks every path.

Better autocomplete

Your editor knows the type of every variable, so typing `user.` lists only the properties that object really has. Calling a function shows its parameter names and types, so you stop flipping to the documentation every few minutes.

Readable, maintainable code

A signature like `function addTax(price: number, rate: number): number` is more trustworthy than a comment, because the compiler keeps checking it. When you change a function, the compiler lists every caller that needs updating, so large projects can be changed with confidence.

Be honest about the limits too. TypeScript adds a build step and a little extra time to write types. More importantly, types do not exist at run time: data from a form, an API or a file is not guaranteed to match the type you wrote, so you convert and check it yourself at that boundary. Types also cannot catch logic bugs such as applying a 20% discount where 10% was meant; you still need tests.

When does a bug get found?
  1. While typing in the editor (TS)
  2. During tsc or CI (TS)
  3. When the tests run
  4. In production, by a user

The earlier a bug is found, the cheaper it is to fix. TypeScript moves type bugs into the first two stages.

General pattern: convert once at the boundary

typescript
function work(input: ExpectedType): Result {
  // inside, every value already has the right type
}

const raw = readFromOutside();      // string, unknown data...
const value = convertOrCheck(raw);  // Number(), parse, validate
work(value);

Parameter types are promises. Convert outside data once, at the boundary, before passing it in; after that, all the inner code can trust its types.

How TypeScript catches the tax bug

This is the same function from the problem, now with types. The commented-out call passes the string directly, so the compiler rejects it. The code below converts the string with `Number()` at the boundary and only then calls the function.

Predict both output lines before you run it. Then uncomment the rejected call and compare the error message your editor shows with the one written in the example.

tax.ts
// Static types turn a silent runtime bug into an editor error.
function addTax(price: number, rate: number): number {
  return price + price * rate;
}

const priceFromForm = "100"; // values from HTML inputs are strings

// addTax(priceFromForm, 0.1);
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

const price = Number(priceFromForm); // convert once, at the boundary
console.log(addTax(price, 0.1));
console.log(addTax(250, 0.05).toFixed(2));

Code breakdown

  1. The contractfunction addTax(price: number, rate: number): number {

    Both `price` and `rate` must be numbers, and so must the result. This one line makes the bug from the problem impossible.

  2. The rejected call// addTax(priceFromForm, 0.1);

    TypeScript inferred `priceFromForm` to be a string, so this call is a compile error. In JavaScript it is the call that produced `"10010"`.

  3. Convert at the boundaryconst price = Number(priceFromForm); // convert once, at the boundary

    `Number()` really converts the value at run time, and its result is typed as number, so `addTax(price, 0.1)` prints `110`.

  4. Type-aware autocompleteconsole.log(addTax(250, 0.05).toFixed(2));

    The editor knows the return type is number, so typing `.` suggests number methods such as `toFixed`. It prints `262.5` with two decimals as `262.50`.

You should see
110
262.50

When TypeScript is worth the most

The payoff is not the same for every project. The table below compares how much TypeScript gives you in different situations. The general rule: the longer the code will live and the more people will touch it, the more TypeScript is worth.

Kind of projectValue of TypeScript
A ten-line throwaway scriptLow; plain JavaScript is fine
An app you will change for monthsHigh; every refactor is safer
Shared code in a large teamVery high; types are contracts between teams
A library other people useVery high; its users get autocomplete

In real projects

Why teams choose TypeScript

TypeScript pays off most in projects where many developers work together. If the backend team renames `price` to `amount` in an API response, updating the shared type makes every frontend component that reads that field fail to compile, instead of `undefined` showing up in production weeks later.

It helps new team members too. Signatures and autocomplete guide them through the codebase, so they do not have to ask which fields each object has. Data from forms, APIs and databases is still converted and checked at the boundary before it gets a type; the Advanced part shows how to do that with zod. Many popular open-source libraries are written in TypeScript or ship type definitions for exactly these reasons.

Common mistakes

Mistakes that waste the benefits

"Converting" a string with `as`

`addTax(priceFromForm as unknown as number, 0.1)` makes the compile error vanish but changes nothing about the value. `as` only tells the compiler 'trust me'; at run time it is still a string and the `"10010"` bug is back. To actually convert, use `Number()` or `parseFloat()`, and check the result for `NaN`.

Treating a clean compile as "no tests needed"

Even if you write `price - price * rate` inside `addTax`, every type is still correct and the compiler stays silent. Types check the shape of values, not whether a calculation is right. A test such as `addTax(100, 0.1) === 110` is still needed.

Expecting the benefits from `any`-heavy code

For a value typed `any`, the compiler checks nothing and the editor cannot autocomplete. A project full of `any` pays the cost of the build step without getting the benefits.

Mini challenge

Mini challenge: an order line

Write typed functions that take a product name, a unit price and a quantity and return a line like `3 x Notebook = 7.50`. One quantity arrives from a form as a string.

  • `lineTotal(unitPrice, quantity)` returns a number
  • `formatLine(name, unitPrice, quantity)` returns a string with the total to two decimals
  • Convert the form value `"3"` at the boundary without using `as`
order-line.ts
// TODO: annotate both parameters and the return type
function lineTotal(unitPrice, quantity) {
  // TODO: multiply
}

// TODO: name is a string; unitPrice and quantity are numbers; returns a string
function formatLine(name, unitPrice, quantity) {
  // TODO: "<quantity> x <name> = <total with 2 decimals>"
}

const quantityFromForm = "3";
// TODO: convert quantityFromForm, then print Notebook (2.5) and Pen (0.75 x 4)

Expected: Prints `3 x Notebook = 7.50` and `4 x Pen = 3.00`.

Show hint

`toFixed(2)` is a number method that returns a string, which matches the return type of `formatLine`.

Show solution
order-line.ts
function lineTotal(unitPrice: number, quantity: number): number {
  return unitPrice * quantity;
}

function formatLine(name: string, unitPrice: number, quantity: number): string {
  const total = lineTotal(unitPrice, quantity).toFixed(2);
  return `${quantity} x ${name} = ${total}`;
}

const quantityFromForm = "3";
const quantity = Number(quantityFromForm);

console.log(formatLine("Notebook", 2.5, quantity));
console.log(formatLine("Pen", 0.75, 4));

Quick quiz 1 / 3

In the example, after `const price = Number(priceFromForm);`, what does `console.log(addTax(price, 0.1))` print?

Quick quiz 2 / 3

What is the right way to pass `priceFromForm` (a string from a form) into `addTax`?

Quick quiz 3 / 3

Which statement about TypeScript's benefits is false?

What to remember

  • Static type checking catches bugs like mixing strings and numbers before the code runs
  • A type-aware editor gives accurate autocomplete and signature help
  • Signatures act as trustworthy documentation and make refactoring safe
  • Really convert outside data at the boundary (`Number()` and friends) instead of using `as`
  • Types cannot catch logic bugs, so tests are still needed

Announcing TypeScript 7.0 — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Why Use TypeScript? | Thuta Learning