0
0
Typescriptprogramming~5 mins

Generic type variance in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is covariance in generic types?
Covariance means a generic type preserves the direction of subtyping. If A is a subtype of B, then Generic<A> is a subtype of Generic<B>. It allows safe substitution when reading values.
Click to reveal answer
beginner
What does contravariance mean in generic types?
Contravariance means a generic type reverses the direction of subtyping. If A is a subtype of B, then Generic<B> is a subtype of Generic<A>. It is useful when a generic type is used for input (like function parameters).
Click to reveal answer
beginner
What is invariance in generic types?
Invariance means no subtyping relationship is preserved between generic types. If A is a subtype of B, Generic<A> and Generic<B> are unrelated types. This happens when a generic type is used for both input and output.
Click to reveal answer
intermediate
How does TypeScript handle variance in function types?
TypeScript treats function parameter types as contravariant and return types as covariant. This means you can pass a function expecting a more general parameter where a more specific one is expected, and return a more specific type than expected.
Click to reveal answer
beginner
Why is understanding generic type variance important?
It helps you write safer and more flexible code by knowing when you can substitute one generic type for another. It prevents bugs related to incorrect assumptions about type relationships in generics.
Click to reveal answer
If Dog is a subtype of Animal, which is true for a covariant generic Box<T>?
A<code>Box&lt;Dog&gt;</code> is a subtype of <code>Box&lt;Animal&gt;</code>
B<code>Box&lt;Animal&gt;</code> is a subtype of <code>Box&lt;Dog&gt;</code>
C<code>Box&lt;Dog&gt;</code> and <code>Box&lt;Animal&gt;</code> are unrelated
DBoth are the same type
Which variance applies when a generic type is used only as a function parameter?
ACovariance
BInvariance
CBivariance
DContravariance
What happens to variance if a generic type is used both as input and output?
AContravariant
BInvariant
CCovariant
DBivariant
In TypeScript, function return types are:
ACovariant
BContravariant
CInvariant
DUnrelated
Why might ignoring variance cause bugs in TypeScript generics?
ABecause it causes syntax errors
BBecause it makes code run slower
CBecause it can allow unsafe substitutions of types
DBecause it prevents using generics
Explain covariance, contravariance, and invariance in generic types with simple examples.
Think about how subtyping changes when used for input or output.
You got /3 concepts.
    Describe how TypeScript treats variance in function types and why it matters.
    Consider how functions accept inputs and produce outputs.
    You got /3 concepts.