Excessive typing for class-based React component

45 Views Asked by At

Flow version: 0.186.0

There's simple React component

//@flow
import * as React from 'react';

export default class App extends React.Component<{}> {
    onClick = (event: SyntheticEvent<HTMLButtonElement>) => {
        console.log(event);
    };

    render(): React.Node {
        return <button onClick={this.onClick}>test</button>
    }
}

I'm using property syntax for onClick to avoid applying .bind(this) every time

Since I export component, flow throws an error

Cannot build a typed interface for this module. You should annotate the exports of this module with types. Missing type
annotation at property `onClick`: [signature-verification-failure]

I'm aware of type-first mode which may want addition export types:

    onClick: ((event: SyntheticEvent<HTMLButtonElement>) => void) = (event: SyntheticEvent<HTMLButtonElement>) => {
        console.log(event);
    };

Question - Is this the only right way to fix this error? Isn't this way too verbose?

1

There are 1 best solutions below

0
Ricola On

This is because the onClick method is public so it needs to be explicitely typed.

You can make Flow understand that it's a "private" method (even if it's not really) but adding a _ prefix:

_onClick = (event: SyntheticEvent<HTMLButtonElement>) => {
        console.log(event);
    };