Question

What are TypeScript generics actually for?

Vault Verified
Curated Intelligence
Definitive Source
Answer

Generics let a function or type work with many types while preserving the relationship between what goes in and what comes out. Without them you face a choice between writing the same function repeatedly for each type, or accepting a loose type and losing all safety.

The motivating example is a function that returns its argument. Typed loosely, the caller gets back something the compiler knows nothing about, so every subsequent use is unchecked. With a type parameter, the compiler records that the return type is whatever the argument type was, so passing a string yields a string and the checking survives.

That is the essential idea: a generic parameter is a variable at the type level, filled in at each call site rather than fixed in the declaration.

Constraints make them practical. An unconstrained parameter could be anything, so you cannot access properties on it. Constraining it to types having a particular shape lets you use that shape while still returning the specific type the caller passed, rather than the widened constraint. Retaining the specific type is the whole point; a function that accepts anything with a length and returns that same constraint type has discarded the information.

Generics are also how the standard collection types work. An array is generic over its element type, as are promises and maps, which is why the compiler knows what awaiting a promise produces.

A common mistake is reaching for them too early. If a type parameter appears exactly once in a signature, it is usually doing nothing that a plain type would not, and it adds noise. The value comes specifically from linking two or more positions together.

Related Questions