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.공변성이란 무엇인가 / seob.dev
TypeScript에서 메서드의 타입을 정의하는 방법은 두 가지가 있습니다. 여러분들은 둘 중 어떤 방식을 선호하시나요? 저는 전자, 그러니까 프로퍼티로서 메서드를 선언하는 방식을 사용해왔습니다. 지금껏 이런 선언 방식은 개인 스타일이라고 생각해서 다른 사람이 저와 다른 방식으로 메서드를 선언하더라도 크게 신경쓰지 않았어요. 그런데 지난 금요일에 메서드 타입 선언 스타일에 대해서 논의하다가, 이 두 가지 방식이 실제로는 미묘한 차이를 가지고 있다는 것을 알게 되었습니다.
https://seob.dev/posts/%EA%B3%B5%EB%B3%80%EC%84%B1%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80/

Seonglae Cho