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:
- Intuitively, covariant type behavior feels more natural and easier to understand
- Languages like C# and Scala provide explicit syntax for covariance and contravariance, but implementing this adds significant complexity
- 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.
Seonglae Cho