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 progress47%
Step 1 of 5
Generic functions
function first<T>(arr: T[]): T | undefined returns element type matching input. Caller picks T via argument.
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 | undefinedDo 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
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.