Variance annotations in TypeScript are explicit modifiers applied to generic type parameters to declare how the subtyping relationship of the generic type relates to the subtyping relationship of its type arguments. By using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
in and out keywords, developers can explicitly define a type parameter as contravariant, covariant, or invariant, bypassing the compiler’s default structural variance inference.
Syntax
Variance annotations are placed directly before the type parameter in a generic declaration:Variance Mechanics
To understand the annotations, consider two types,Sub and Super, where Sub is a subtype of Super (e.g., Sub is assignable to Super).
Covariance (out)
The out modifier declares that the generic type’s subtyping direction matches the type parameter’s subtyping direction. It indicates that the type parameter is strictly produced (emitted) by the type.
- Rule: If
SubextendsSuper, thenGeneric<Sub>is assignable toGeneric<Super>. - Enforcement: The compiler will throw an error if an
outtype parameter appears in a contravariant position (e.g., as a method argument).
Contravariance (in)
The in modifier declares that the generic type’s subtyping direction is the exact reverse of the type parameter’s subtyping direction. It indicates that the type parameter is strictly consumed (received) by the type.
- Rule: If
SubextendsSuper, thenGeneric<Super>is assignable toGeneric<Sub>. - Enforcement: The compiler will throw an error if an
intype parameter appears in a covariant position (e.g., as a return type).
Invariance (in out)
Applying both modifiers declares that the generic type requires strict equality of the type parameter. Subtyping is rejected in both directions. It indicates the type parameter is both consumed and produced.
- Rule:
Generic<Sub>andGeneric<Super>are mutually unassignable. Exact type matching is required.
Structural Visualization
The following code demonstrates the mechanical assignment rules enforced by variance annotations:Compiler Validation
When a variance annotation is applied, TypeScript statically verifies that the internal structure of the type adheres to the declared variance contract.Master TypeScript with Deep Grasping Methodology!Learn More





