Contravariance

Creator
Creator
Seonglae ChoSeonglae Cho
Created
Created
2021 Aug 17 4:6
Editor
Edited
Edited
2025 Oct 16 12:48

Contravariance

Contravariance refers to the behavior in TypeScript's strictFunctionTypes mode, where function type parameter positions are checked contravariantly instead of bivariantly.

Why weren't function parameters contravariant from the start?

While it seems natural for function parameters to be contravariant, TypeScript initially implemented them bivariantly. Here's why:
  1. Intuitively, covariant type behavior feels more natural and easier to understand
  1. Languages like C# and Scala provide explicit syntax for covariance and contravariance, but implementing this adds significant complexity
  1. Due to these implementation challenges and complexity concerns, TypeScript initially chose bivariance as a pragmatic compromise

Understanding contravariance

Logger<string | number> actually becomes a subtype of Logger<number>. This behavior is called contravariance.
When you enable strictFunctionTypes, all function parameters operate contravariantly, providing stronger type safety.
 
 
 
 
 

Recommendations