Back to Blog
TypeScriptVarianceGenericsType Safety

TypeScript Variance Annotations Guide

Master TypeScript variance annotations (in/out) for precise generic type parameter control.

B
Bootspring Team
Engineering
October 2, 2019
6 min read

Variance annotations explicitly declare how generic type parameters can be used. Here's how to apply them.

Basic Concepts#

Loading code block...

Covariance with out#

Loading code block...

Contravariance with in#

Loading code block...

Combined Annotations#

Loading code block...

Type Checking Improvements#

Loading code block...

Callback Patterns#

Loading code block...

State Management#

Loading code block...

Collection Types#

Loading code block...

Observer Pattern#

Loading code block...

Builder Pattern#

Loading code block...

Error Handling#

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles