Variance annotations explicitly declare how generic type parameters can be used. Here's how to apply them.
Basic Concepts#
Covariance with out#
Contravariance with in#
Combined Annotations#
Type Checking Improvements#
Callback Patterns#
State Management#
Collection Types#
Observer Pattern#
Builder Pattern#
Error Handling#
Best Practices#
When to Use:
✓ Library/framework code
✓ Generic interfaces
✓ Complex type hierarchies
✓ API design
Benefits:
✓ Explicit variance intent
✓ Better error messages
✓ Faster type checking
✓ Clearer documentation
Patterns:
✓ out for producers/getters
✓ in for consumers/setters
✓ No annotation for invariant
✓ Combine for transformers
Avoid:
✗ Overusing on simple types
✗ Ignoring variance errors
✗ Breaking encapsulation
✗ Adding without understanding
Conclusion#
Variance annotations (in/out) make generic type parameter usage explicit. Use out for types that only produce values (covariant), in for types that only consume values (contravariant), and no annotation for types that do both (invariant). This improves type safety and helps TypeScript provide better error messages.