Chapter 1

From JS to TS: Catching 3 Runtime Error Classes at Compile Time

Why TypeScript

Not because "type safety" sounds impressive, but because JavaScript has three error classes that keep showing up in production. TypeScript catches all three the moment you save the file.

Error class 1: Property access errors

// JS: crashes at runtime
function getUsername(user) {
  return user.profile.name; // TypeError: Cannot read properties of undefined
}

getUsername({ name: "Alice" }); // user.profile is undefined
// TS: compile-time error, zero runtime cost
interface User {
  name: string;
  profile?: { name: string };
}

function getUsername(user: User): string {
  return user.profile?.name ?? user.name; // must handle undefined
}

Error class 2: Function argument type mismatches

// JS: silently wrong
function add(a, b) { return a + b; }
add("5", 3); // "53" โ€” string concatenation, not addition
// TS: immediate error
function add(a: number, b: number): number { return a + b; }
add("5", 3); // Error: Argument of type 'string' is not assignable to parameter of type 'number'

Error class 3: API response shape changes

// Backend renamed a field โ€” TS immediately marks every affected line
interface ApiResponse {
  userId: number;  // was user_id
  email: string;
}

// Every access to response.user_id lights up red โ€” instead of waiting for user reports

How TypeScript Works

TypeScript is a typed superset of JavaScript: every valid JS file is a valid TS file.

TypeScript source (.ts)
    โ†“ tsc compiles
JavaScript file (.js)  โ†  what the browser/Node.js actually runs

Key point: type information is completely erased after compilation. No runtime type checking, no performance overhead. TypeScript is a smarter editor and compiler, nothing more.


5-Minute Local Setup

Recommended: use tsx to run TS files directly โ€” no compile step

npm install -g tsx

# run directly
tsx your-file.ts

# watch mode
tsx watch your-file.ts

For a real project: initialize TypeScript config

npm init -y
npm install -D typescript @types/node

# generate tsconfig.json (deep-dive in Chapter 16)
npx tsc --init

Structural Typing vs Nominal Typing

This is the core of understanding TypeScript. TypeScript checks type compatibility by shape (structure), not by name.

interface Point2D { x: number; y: number; }
interface Vector2D { x: number; y: number; }

function printPoint(p: Point2D) {
  console.log(p.x, p.y);
}

const v: Vector2D = { x: 1, y: 2 };
printPoint(v); // โœ… valid โ€” shapes match, names don't matter

This is completely different from Java/C# nominal typing โ€” in Java, Point2D and Vector2D are incompatible types even if they have identical fields.

Practical implication:

interface Named { name: string; }

class Dog {
  name: string;
  constructor(name: string) { this.name = name; }
}

function greet(n: Named) { console.log(n.name); }

greet(new Dog("Buddy")); // โœ… valid โ€” Dog has a name property, shape matches

The Real Cost of any

any is an escape hatch. Every time you use it, you're digging a hole:

function processData(data: any) {
  return data.items.map((item: any) => item.value); // zero type checking
}

// Three months later, the data shape changes.
// TS won't tell you โ€” you used any, you're on your own.
// Result: runtime TypeError in production

any is contagious:

const x: any = getExternalData();
const y = x.foo;        // y is also any
const z = y.bar.baz;    // z is still any
// the entire chain loses type protection

Replace any with unknown โ€” it forces you to do a type check before use. Covered in Chapter 2.


Key Takeaways

Point Details
TS is a superset of JS All JS code is valid TS
Types exist at compile time only Zero runtime overhead
Structural type system Shape compatibility, not name matching
3 error classes caught Property access, argument types, API shape changes
Avoid any Use unknown to keep the type chain intact

Next chapter: Type Inference and Annotation Boundaries โ€” how much TypeScript can infer on its own, and when you must write explicit type annotations.

Rate this chapter
4.7  / 5  (108 ratings)

๐Ÿ’ฌ Comments