Manuals / TypeScript / Chapter 6

C · Reuse · intermediate · Week 3 · Chapter 6 of 11

Generics

Generics are type parameters — reusable functions and types that work across shapes while preserving type relationships. <T> on functions, interfaces, and classes. Constraints with extends. Avoid generic abuse — if T appears once, skip it.

Path progress
47%

Step 1 of 5

Generic functions

function first<T>(arr: T[]): T | undefined returns element type matching input. Caller picks T via argument.

Generic functionsDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Generic functionsdrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

Example

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

const n = first([1, 2, 3])     // number | undefined
const s = first(["a", "b"])   // string | undefined

Do this now

Write first, last, and findById<T>(items: T[], id: number, key: keyof T).

Was this step clear?
Chapter learning outcomes
  • Generic functions
  • Generic interfaces
  • Constraints (extends)
  • Default type params
  • Generic pitfalls
Chapter videos

Fireship

TypeScript in 100 seconds

Types without the enterprise fog.

Open on YouTube →

Clear these before you leave

Side quest

Generic cache

Create Cache<T> class with get(key: string): T | undefined, set(key: string, value: T). Type-safe for any T.