Skip to content
TypeScript Essentials

Lesson 2 of 6 · 22 min

x
2/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Generics & Type Parameters

Too loose, too narrow, or generic with a constraint
Too loose, too narrow, or generic with a constraint

Generics allow you to write reusable functions, interfaces, and classes that operate over variable types while preserving complete type safety. Instead of relying on any (which disables type checking), generics use type parameters (e.g., <T>) that TypeScript infers or receives from callers.

Type parameters can be restricted using generic constraints (<T extends HasId>). Constraints guarantee that whatever argument type a caller passes, it must satisfy specific structural requirements (such as possessing an id property).

Before
Unsafe Type Erasure with `any`
1// ❌ Loses return type information2function getFirstItem(items: any[]): any {3  return items[0];4}
After
Type-Safe Generic Function with Constraint
1interface Identifiable {2  id: string | number;3}4 5// ✅ Preserves exact return type T and enforces id property6function getFirstItem<T extends Identifiable>(items: T[]): T {7  return items[0];8}

Exercise

Write a generic wrapper function createApiResponse<T>(data: T) that returns { data: T; status: number; timestamp: string }.

Check your understanding

  • Why is a generic function better than using any?Show answer

    Answer

    Generics preserve type relationships between inputs and output return values, keeping full autocomplete and type-checking intact.
  • What does the extends keyword do inside generic parameter angle brackets <T extends Lengthwise>?Show answer

    Answer

    It places a constraint on T, enforcing that passed arguments must have all properties defined in Lengthwise.
Previous

Progress is saved in this browser.

Next Lesson