# TypeScript — Types That Catch Bugs Before Runtime

## What is TypeScript?

TypeScript is JavaScript with static typing. A compiler checks types at build time; invalid code fails before it runs.

**JavaScript (runtime error):**
```javascript
function greet(name) {
  return name.toUpperCase();
}
greet(42);  // Runtime: name.toUpperCase is not a function
```

**TypeScript (compile-time error):**
```typescript
function greet(name: string) {
  return name.toUpperCase();
}
greet(42);  // Error: Argument of type 'number' is not assignable to parameter of type 'string'
```

## Basic Types

```typescript
let n: number = 42;
let s: string = "hello";
let b: boolean = true;
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ["a", 1];
let nothing: void = undefined;
```

TypeScript infers types when you assign directly, so explicit annotations are often optional.

## Interfaces

Define object shapes:

```typescript
interface User {
  id: number;
  name: string;
  email?: string;  // optional
}
const u: User = { id: 1, name: "Alice" };
```

Interfaces support inheritance and declaration merging.

## Type Aliases

Alternative to interfaces for object shapes and unions:

```typescript
type ID = string | number;
type Point = { x: number; y: number };
```

## Unions

A value can be one of several types:

```typescript
type Status = "pending" | "success" | "error";
function handle(s: Status) { /* ... */ }
```

## Generics

Reusable types parameterized by other types:

```typescript
function identity<T>(x: T): T {
  return x;
}
const n = identity(42);   // T inferred as number
const s = identity("hi"); // T inferred as string
```

```typescript
interface Box<T> {
  value: T;
}
const box: Box<number> = { value: 42 };
```

## Type Narrowing

Narrow types with conditionals so TypeScript knows the type in each branch:

```typescript
function padLeft(value: string | number): string {
  if (typeof value === "number") {
    return " ".repeat(value);  // value is number here
  }
  return value;  // value is string here
}
```

Common narrowing: `typeof`, `instanceof`, `in`, discriminated unions.

## Utility Types

Built-in helpers:

| Type | Purpose |
|------|---------|
| `Partial<T>` | All properties optional |
| `Required<T>` | All properties required |
| `Pick<T, K>` | Select specific keys |
| `Omit<T, K>` | Exclude specific keys |
| `Record<K, V>` | Map keys to value type |

```typescript
type UserUpdate = Partial<User>;  // All fields optional
type NameOnly = Pick<User, 'name'>;
```

## When Types Catch Bugs

| JS Bug | TS Catches It |
|--------|----------------|
| `undefined` property access | Strict null checks |
| Wrong argument type | Function parameter types |
| Typo in property name | Object shape checking |
| Missing required field | Interface compliance |
