facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.08k stars 1.86k forks source link

Support for Comparables with `valueOf` #2406

Open wessberg opened 8 years ago

wessberg commented 8 years ago

Consider this:

interface Comparable {
    valueOf(): number;
}

class Comparer<Key:Comparable> {

    greater (first: Key, second: Key): boolean {
        // flow error: Cannot be compared to Comparable
        return first > second;
    }
}

The valueOf() method gets special treatment in Javascript and returns the primitive value for an Object type.

It can be implemented by any object so that they can be used in comparisons with the '<', '==', '===' and '>' operators. However, from the example above it appears to be the case that flow doesn't understand that the valueOf() method in the Comparable interface can be used without calling first.valueOf() > second.valueOf() directly.

I'd love to see this implemented in flow. It will be nice if flow throws the error only if the given item is an object type and doesn't implement valueOf().

dckc commented 7 years ago

I'm looking for a bound on T that would let me use this min function with Date objects. Am I currently out of luck?

// ack: Linus Unnebäck Nov 18 '12
// http://stackoverflow.com/a/13440842
function min/*:: <T>*/(arr /*: Array<T>*/) {
    return arr.reduce((p, v) => p < v ? p : v );
}