TypeScript Essentials (for Full-Stack AI Apps)
Core concepts
| Feature | Use |
|---|---|
| Union types + narrowing | Narrow a wide type to a specific one with if, in, typeof or a discriminant field |
| Discriminated unions | Distinguish several shapes by one shared field (such as type / status); ideal for modelling task states and SSE events |
unknown vs any | Treat external data as unknown first and use it only after validation; any switches type checking off |
| Generics | Write reusable API clients and table components |
satisfies | Checks that a value matches a type while keeping the more precise inferred type |
| Utility types | Partial, Pick, Omit, Record, ReturnType, etc. |
How it works: types exist only at compile time
TypeScript types are erased after compilation and nothing is checked at runtime. So data from the backend, an LLM or user input must be validated at runtime (e.g. with Zod) before you get a type you can trust.
In practice
Modelling task state with a discriminated union
ts
type Task =
| { status: 'queued'; id: string }
| { status: 'running'; id: string; step: string; progress: number }
| { status: 'needs_review'; id: string; reason: string }
| { status: 'done'; id: string; result: ContractFields }
| { status: 'failed'; id: string; error: string; retryable: boolean }
function label(t: Task) {
switch (t.status) {
case 'running': return `${t.step} ${t.progress}%` // step is accessible here
case 'failed': return t.retryable ? 'Failed, retryable' : 'Failed'
default: return t.status
}
}Runtime validation: Zod
ts
import { z } from 'zod'
const SseEvent = z.discriminatedUnion('type', [
z.object({ type: z.literal('token'), text: z.string() }),
z.object({ type: z.literal('done'), stop_reason: z.string() }),
])
const evt = SseEvent.parse(JSON.parse(data)) // throws if it doesn't matchKeeping frontend and backend types in sync
FastAPI generates OpenAPI docs automatically, so you can generate TS types from the OpenAPI spec with a tool such as openapi-typescript instead of writing them twice.
Common pitfalls
- Overusing
asassertions:data as Taskonly fools the compiler; the runtime data may still be wrong. strictnot enabled: new projects should turn onstrict: true.- Handling API responses as
any: errors travel all the way to the UI before they surface.
Common interview questions
- What's the difference between
unknownandany? - What is a discriminated union? Give an example you've used.
- Can TypeScript guarantee type safety at runtime? How do you handle external data?
- What's the difference between
interfaceandtype?
Sources
- TypeScript Handbook: Narrowing — narrowing, discriminated unions
- TypeScript Handbook: Everyday Types
- TypeScript 4.9 Release Notes: satisfies
- Zod Docs
- openapi-typescript
