DELAPARRA
Index
Color
NL
Category: Programming paradigms

Generic Constraint

Explained by Updated

What is Generic Constraint?

Generic Constraint: A restriction on what T can be, e.g. "T must implement Comparable" — needed if the generic code calls methods on T. A generic constraint limits which types can be used with generic code. function max<T extends Comparable>(a: T, b: T) accepts any type, as long as it can be compared.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about Generic Constraint

How is Generic Constraint used in practice?

Without a constraint, generic code can only treat values as opaque. With one, it can safely call the methods the constraint guarantees, and the compiler checks this for every use.

What should you keep in mind with Generic Constraint?

TypeScript, Java, C# and Rust all support this. PHP has no native generics, but static analysis tools like PHPStan and Psalm let you express them in docblocks, such as @template T of Model. That gives editors and checkers the same information, so a function that works on any model still knows which model it returns. The benefit is fewer runtime surprises and better autocompletion.

At a glance

CategoryProgramming paradigms
Explained by
Updated

More Programming paradigms terms

All terms starting with G

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.