generic constraint

A rule on a type parameter that limits which types may fill it, such as requiring a class, a particular interface or a certain shape.

In more detail

Without a constraint a type parameter could be anything, so generic code can do almost nothing with it. A constraint lets the code rely on what the constraint promises, and callers passing an unsuitable type get a compile error. C# writes constraints with where, and TypeScript writes them with extends.

Examples

C#: where TKey : notnull
TypeScript: T extends { id: string }

Related terms

Taught in

References