How do generic type parameters complicate structural comparisons, particularly regarding 'bivariant' method comparison?
Short answer
By default, TypeScript compares METHOD parameters BIVARIANTLY (allowing assignment in either direction, for practical/legacy reasons) but compares STANDALONE function type parameters (arrow function properties) more strictly, CONTRAVARIANTLY — meaning identically-shaped generic…
Advertisement
AModel answer
By default, TypeScript compares METHOD parameters BIVARIANTLY (allowing assignment in either direction, for practical/legacy reasons) but compares STANDALONE function type parameters (arrow function properties) more strictly, CONTRAVARIANTLY — meaning identically-shaped generic interfaces can behave differently for type-safety purposes depending on whether a callback is declared as a method shorthand or an arrow-function-typed property.
interface Comparer<T> {
compare(a: T, b: T): number; // method syntax: bivariant, more lenient
compareArrow: (a: T, b: T) => number; // arrow property: contravariant, stricter with strictFunctionTypes
}Real-world example
Debugging a subtle type-safety difference between two seemingly-identical callback interface members, one declared as a method and one as an arrow-typed property.
Likely follow-ups
- How does the 'strictFunctionTypes' compiler option specifically affect this bivariance for standalone (non-method) function types?
Related topics