Q41. What are covariance and contravariance at a high level?
Variance describes how subtyping relationships behave when types are used inside another type. Return positions are generally covariant: a function returning a more specific value can often stand in for one returning a broader value. Parameter positions are checked contravariantly in strict function type positions, reflecting that a consumer may pass any value promised by the contract.
Function compatibility must ensure the implementation can safely accept every argument the caller may provide.
Note
Interview approach: define the concept, explain why it matters, then mention one trade-off or limitation.
TypeScript concept
// Illustrative TypeScript contract
type Identifier = string;
const id: Identifier = "item-1";💡 The example demonstrates the compile-time contract discussed in this question.
Key Takeaways
- Explain the concept in your own words.
- Know the practical trade-off and its limits.
- Use a small example to demonstrate the idea.
Knowledge Check
For callback parameters, why must the implementation accept the values promised by the caller?