Consider the following generic function in Flow:
function lessThen<T>(a: T, b: T) {
return a < b;
}
The intention here is to instantiate lessThen with a type that allows the < operator like number or string.
In this form Flow complains about it:
return a < b;
^ Cannot compare `T` [1] to `T` [2]. [invalid-compare]
References:
1: function lessThen<T>(a: T, b: T) {
^ [1]
1: function lessThen<T>(a: T, b: T) {
^ [2]
So I suppose I need to constrain T in lessThen to support <. But how do I do that? I was looking to something like build-in type CanUseCompareOperators so I can write:
function lessThen<T: CanUseCompareOperators>(a: T, b: T) {
return a < b;
}
but I cannot find any.
Although in this toy example I can drop the generics and let Flow infere the type, in the real code I need this to work for a methods in a generic class when dropping generics is not an option like in:
class Foo<Key, Value> {
binarySearch() {
// code that uses < and > to compare keys
}
}