🔤

TypeScript Generics — Understanding T Once and for All

Using "types decided later" in functions, classes, and interfaces

T means "decided at call time." first([1,2,3]) → TypeScript infers T=number.

Common Patterns

Constraint: <T extends HasId> — T must satisfy HasId
keyof: <K extends keyof T> — K must be one of T's keys
Utility types: Partial, Required, Pick, Omit — all implemented with generics

type Partial<T> = { [K in keyof T]?: T[K] };

If you can read this line, you understand TypeScript generics.

Key Points

1

T is a placeholder for unknown type — determined at call time

2

T extends Constraint adds limits — conditions T must satisfy

3

keyof T extracts object keys as types

4

Utility types like Partial<T>, Pick<T,K> implemented with generics + mapped types

Use Cases

API clients — fetch<T>(url): Promise<T> for auto response type inference Component props — creating generic components in React