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>?✗ Incorrect
Covariance preserves subtyping direction, so
Box<Dog> is a subtype of Box<Animal>.Which variance applies when a generic type is used only as a function parameter?
✗ Incorrect
Function parameters are contravariant because the subtyping direction reverses for inputs.
What happens to variance if a generic type is used both as input and output?
✗ Incorrect
Using a generic type both as input and output makes it invariant, so no subtyping relationship is preserved.
In TypeScript, function return types are:
✗ Incorrect
Function return types are covariant, meaning they preserve subtyping direction.
Why might ignoring variance cause bugs in TypeScript generics?
✗ Incorrect
Ignoring variance can allow substituting incompatible types, leading to runtime errors.
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.