facebook / flow

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

Generics with class instance fields #4743

Open kohver opened 7 years ago

kohver commented 7 years ago

Please look at following code:

type TestProps<T> = {
    item: T,
    onSelect: (item:T) => void,
};

const B = <T>(props:TestProps<T>) => {
    // ...
};

class A<T> extends React.Component<TestProps<T>> {
    render() {
        return (
            <B
                item={this.props.item}
                //    ^^^^^^^^^^^^^^^ T. This type is incompatible with the expected param type of
                onSelect={this.onSelect}
            />
        );
    };

    onSelect = (item:T) => {
        //           ^ some incompatible instantiation of `T`
        this.props.onSelect(item);
    };
}

👉 Try it


Seems that the error caused by class instance field onSelect.

The only workaround I found is to pass this.onSelect.bind(this) in render method and don't use onSelect = () => {} syntax:

    ...
    onSelect(item:T) {
        this.props.onSelect(item); // No errors!
    }
    ...

👉 Try it

vkurchatkin commented 7 years ago

Here is a minimal example:

class A<T>  {
    a() {
        (this.b: T => void)
    };

    b = (item:T) => {};
}

Flow seems to be unable to infer type of b correctly.