Advanced: TypeScriptAdvanced7 min21 / 23

TypeScript: Adding Types

TypeScript is JavaScript with a type checker — annotate values, let inference do the rest, and catch whole classes of bugs before you run.

TypeScript (TS) is a superset of JavaScript: every valid JS file is valid TS, plus you can add type annotations. A compiler checks those types and flags mistakes before the code runs, then strips the types away to produce plain JavaScript.

annotations + inference
let title: string = "Quest";
let count: number = 3;
let done: boolean = false;

// inference: TS already knows this is a number
let score = 10;      // score: number

function double(n: number): number {
  return n * 2;
}

console.log(double(score));

You rarely annotate everything — TypeScript infers most types. You mostly annotate function parameters and tricky spots; the compiler propagates the rest.

#Catching bugs early

the checker complains — before runtime
function greet(name: string) {
  return "Hi, " + name.toUpperCase();
}

greet("Ada");   // ✅ fine
// greet(42);   // ❌ TS error: number is not assignable to string
//              (a real bug caught before the code ever runs)
console.log(greet("Ada"));
Note

Types vanish at runtime

TypeScript types exist only during development and compilation. The emitted JavaScript has no types — so TS adds zero runtime cost. (When you Run this lesson's code, the types are stripped and the plain JS executes.)

Quick check

What is the main benefit of TypeScript over plain JavaScript?

Key takeaways

  • TypeScript = JavaScript + a compile-time type checker.
  • Annotate with `name: type` (`string`, `number`, `boolean`, arrays, etc.).
  • TS infers most types — you mainly annotate function parameters.
  • Type errors are caught before running; types are stripped from the emitted JS (no runtime cost).
Practice challenges
Test yourself · earn XP
0/3
Fix the bug#1

TypeScript reports an error on the last line. Why is that a good thing?

fix-bug
function greet(name: string) {
  return 'Hi ' + name.toUpperCase();
}
greet(42);
Predict the output#2

What type does TypeScript infer for `score` here?

predict-output
let score = 10;
Fill in the blank#3

Annotate the parameter so it must be a number.

function square(n number) {
  return n * n;
}
Your turn
Practice exercise

Annotate this function so it only accepts two numbers and returns a number:

``ts function add(a, b) { return a + b; } ``

Try it live — edit the code and hit Run to see the output:

solution.js · editable