← Back to the Build Your Homepage series
πŸ”·
EPISODE 05
<T> Β· constraints Β· keyof Β· utility types

Generics

Write reusable, type-safe abstractions with generics. Master constraints, keyof, and the built-in utility types Partial, Pick, Omit, Record.

genericsTypeVarkeyofutility types
Duration
⏱ About 2 hours
Level
πŸ“Š Intermediate+
Prerequisite
🎯 ts-03
OUTCOME
Build flexible generic functions and types reused across modules

What you'll learn

  • 1Write generic functions and classes
  • 2Constrain type parameters with extends
  • 3Use keyof to refer to property names
  • 4Apply utility types: Partial, Required, Pick, Omit, Record

1. Generic Functions

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

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

2. Constraints with extends

typescript
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest("hello", "hi");
longest([1,2,3], [4,5]);

3. keyof

typescript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 1, name: "Alice" };
const n = getProp(user, "id");     // number
const s = getProp(user, "name");   // string
// getProp(user, "email");          // error

4. Utility Types

UtilityEffect
Partial<T>All properties optional
Required<T>All properties required
Pick<T, K>Pick a subset of keys
Omit<T, K>Remove keys
Record<K, V>Build an object type with given keys/values
Readonly<T>All properties readonly
ReturnType<F>Return type of a function
typescript
type User = { id: number; name: string; email: string };

type UserUpdate = Partial<User>;       // { id?, name?, email? }
type UserName   = Pick<User, "name">;   // { name: string }
type NoEmail    = Omit<User, "email">;
type UsersById  = Record<number, User>; // { [id: number]: User }
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—