Overview - Covariance and contravariance
What is it?
Covariance and contravariance describe how types relate when you replace one type with another in programming. They explain when you can safely use a more specific or more general type instead of the original. This helps TypeScript check if your code will work without errors when types change. Understanding these concepts makes your code more flexible and safe.
Why it matters
Without covariance and contravariance, TypeScript would be too strict or too loose, causing many bugs or limiting how you write code. These concepts let you reuse functions and objects safely with different but related types. They help prevent errors when passing data around, making your programs more reliable and easier to maintain.
Where it fits
Before learning covariance and contravariance, you should understand basic TypeScript types, interfaces, and function types. After this, you can explore advanced type features like generics, mapped types, and conditional types to write even more flexible code.