QuestionsTypeScript

Why generics? identity + a constrained generic

GenericsEasyTypeScript

Explain generics with a concrete example. Then constrain a generic so it only accepts objects with an `id`.

What it tests

Whether you understand generics preserve type relationships instead of erasing to `any`.

Approach & answer

Generics let a function/type work over many types while KEEPING the relationship between input and output. identity<T>(x: T): T returns exactly what it got — pass a string, get a string back (not any). `extends` constrains the type parameter: <T extends { id: string }> means T can be any object as long as it has an id, and you keep full type safety on that field. The mental model: a generic is a type-level function — it takes types as parameters and produces a type. Inference usually fills them in for you (you rarely write identity<string>(x) — TS infers T from the argument), which is why generics feel invisible until you need to constrain or relate them. Common patterns: a constraint (<T extends HasId>), a default (<T = string>), and relating two params (function pick<T, K extends keyof T>(obj: T, key: K): T[K] — the return type is derived from which key you pass). Prefer generics over `any` or overloads whenever the output type depends on the input type; they preserve type information all the way through the call.

Use this technique when

Reusable utilities/hooks/containers: a typed useFetch<T>(), a Repository<T>, array helpers that keep element types.

References

ts