Skip to main content
A generic constraint in TypeScript restricts the set of types that can be substituted for a generic type parameter. By enforcing a specific structural contract using the extends keyword, constraints guarantee that a generic type possesses predefined properties, methods, or signatures. This allows the TypeScript compiler to safely resolve and validate property accesses on instances of that generic type during static analysis. Without a constraint, a generic type parameter T is treated as an opaque type (effectively unknown), meaning the compiler will reject any attempt to access properties on it.

Base Syntax

The constraint is declared immediately after the type parameter using the extends keyword, followed by the target type (which can be an interface, type alias, class, or primitive).

Compiler Behavior: Unconstrained vs. Constrained

When a generic is unconstrained, the compiler cannot guarantee the existence of any specific members.
Applying a constraint informs the compiler of the minimum structural requirements T must fulfill. Because TypeScript uses structural typing, any type passed to T must contain at least the properties defined in the constraint.

Advanced Constraint Mechanics

1. Constraining with Type Parameters (keyof)

A type parameter can be constrained by the shape of another type parameter within the same signature. This is heavily utilized with the keyof operator to enforce that a generic key strictly exists on a generic object.
In this structure, K is constrained to the union of literal types representing the keys of T.

2. Multiple Constraints via Intersection

TypeScript does not support a comma-separated list of constraints. To enforce multiple constraints simultaneously, you must use an intersection type (&).

3. Constraints with Default Types

Generic constraints can be combined with generic default types. The default type must strictly satisfy the constraint.

4. Primitive Constraints

Constraints are not limited to object shapes; they can restrict type parameters to specific primitives or literal unions.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More