05

Advanced TypeScript

Generics, narrowing, the runtime gap

GoalMove past interface/type into the part of TypeScript that catches bugs. Understand that types are compile-time only — and what that means for API data.

Lessons

Types are erased at runtime

  • Types check your code, not your data
  • A value from fetch / JSON.parse / localStorage is not validated by TS just because you annotated it
ts
const user: User = await res.json(); // TS believes you — runtime could be anything

For true runtime safety on external data, use Zod or similar runtime validators.

any vs unknown

`any` — disables type checking entirely. Contagious and dangerous. `unknown` — safe counterpart. Forces you to narrow before use.

ts
const a: any = getData();
a.foo.bar(); // no error — TS gave up

const b: unknown = getData();
b.foo.bar(); // ❌ error — must narrow first
if (typeof b === "object" && b !== null && "foo" in b) {
  // now TS allows it
}

Rule: never use any to silence an error. Use unknown and narrow.

Generics

Generics let you write reusable code without losing type information.

ts
// Without: loses type
function first(arr: any[]): any { return arr[0]; }
const x = first([1,2,3]); // x is 'any' — useless

// With generic: preserves type
function first<T>(arr: T[]): T { return arr[0]; }
const y = first([1,2,3]);  // y is 'number' ✅
const z = first(["a","b"]); // z is 'string' ✅

You use generics constantly: useState<number>(0), Promise<User>, Array<string>.

Discriminated Unions

The single most useful TS pattern for frontend state:

ts
type State =
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; message: string };

function render(s: State) {
  if (s.status === "success") return s.data.name; // TS knows data exists
  if (s.status === "error") return s.message;     // TS knows message exists
  // loading — TS knows neither exists here
}

Makes impossible states impossible — you cannot accidentally access data while loading.

Challenges2

Write working code. Run to see output. Check to grade.

CH1
Write a generic identity function
Warm-up

The function below uses any and loses type information. Rewrite it as a generic function identity<T> that returns the same type it receives. Log the result.

JavaScript
CH2
Utility type composition
Hard
  • Takes id: number (required, separate param)
  • Takes changes — any subset of the OTHER fields (all optional, id excluded)

Then log "types work" if TypeScript compiles (it will if your types are correct).

ts
interface Product { id: number; name: string; price: number; stock: number; }
JavaScript

References