3. TypeScript Fundamentals & Type Thinking
Generics (<T>), Constraints & Utility Types (Pick, Omit, Partial, Record)
Write reusable, type-safe functions and API wrappers with TypeScript Generics (<T>), extends constraints, keyof, and built-in DTO utility types like Partial, Pick, Omit, and Record.
- Write generic functions and wrapper interfaces (`ApiResponse<T>`) that preserve caller types
- Restrict generic type parameters cleanly using `extends` and `keyof`
- Transform existing interfaces into PATCH/public/lookup types with Partial, Pick, Omit, and Record
Without Generics, writing a reusable firstItem(arr) helper forces an ugly choice: duplicate it for Course[], User[], and string[], or fall back to any[] and lose autocomplete!
Generics (<T>) act like type parameters—letting one function or interface adapt to whatever concrete type the caller passes while keeping 100% type safety.
1. Generic Functions & Wrapper Types (<T>)
// T captures the exact element type passed by the caller!
function firstItem<T>(items: readonly T[]): T | undefined {
return items[0];
}
const num = firstItem([10, 20, 30]); // inferred: number | undefined
const str = firstItem(["ts", "js"]); // inferred: string | undefined
// Generic API envelope shared across every endpoint:
interface ApiResponse<TData> {
ok: boolean;
data: TData;
timestamp: string;
}Constraining Generics with extends & keyof
When a generic helper needs to read .id or look up a property safely, constrain <T> using extends:
function indexById<T extends { id: string }>(items: readonly T[]): Record<string, T> {
const map: Record<string, T> = {};
for (const item of items) {
map[item.id] = item;
}
return map;
}
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]; // Autocompletes valid keys AND preserves exact return type!
}2. Essential Utility Types for Everyday Apps
User (Source)
id, name, email, passwordHash
Omit<User, "passwordHash">
PublicUser (safe for UI!)
Partial<Pick<User, "name" | "email">>
PATCH update payload
Derive update payloads and public views from one source-of-truth User interface using Pick, Omit, and Partial.
Never copy-paste an interface 3 times for Create, Update, and Public DTOs—derive them from one source of truth:
| Utility Type | What It Produces | Real-World Use |
|---|---|---|
Partial<T> | Makes all fields optional (?) | Settings defaults or PATCH payloads |
Required<T> | Makes all optional fields required | Resolved config objects |
Pick<T, K> | Keeps only listed keys K | Lightweight card summaries (Pick<Course, "id" | "title">) |
Omit<T, K> | Removes listed keys K | Omit<User, "passwordHash"> or Omit<Task, "id"> on create |
Record<K, V> | Dictionary mapping keys K to values V | Lookup maps (Record<string, Course>) or status labels |
Writing const LABELS: Record<OrderStatus, string> = { pending: "Pending", paid: "Paid", cancelled: "Cancelled" }; guarantees at compile time that every union member has a label!
Try It Yourself in the Playground
Test the runtime behavior of indexById (Record<string, T>) and pluck (keyof) cleanly below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Using TypeScript utility types on interface Task { id: number; title: string; completed: boolean; ownerId: number }, how do you define TaskPatch so callers can optionally update only title or completed (never id or ownerId)?
Quick Checkpoints
What is the difference between function wrap(x: any): any and function wrap<T>(x: T): T?
Which TypeScript utility type creates a new type from User with passwordHash removed?