Checking React with Flow

ReactEurope 2016

Oliver Zeigermann / @DJCordhose

djcordhose.github.io/react-intro-live-coding/2016_react_europe.html

Flow is a static type checker, designed to quickly find errors in JavaScript applications

Example #1: Simple Check with Type Inference


const element = 'just a string'; // type is interred as string
ReactDOM.render(element, mountNode);
            

Message from flow

src/step-1-typed/client/main.js:12
 12: ReactDOM.render(element, mountNode);
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method `render`
 12: ReactDOM.render(element, mountNode);
                     ^^^^^^^ string. This type is incompatible with
237:     element: React$Element<Config>,
                  ^^^^^^^^^^^^^^^^^^^^^ React$Element.
See lib: /private/tmp/flow/flowlib_1ddc81a6/react.js:237

Example #2: Type Declarations


type State =  {
    greeting: string;
};
        

type Props = {
    // ERROR: trying to assign this boolean to state
    // greeting: boolean
    greeting: string
};
        

class HelloMessage extends React.Component<any, Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {greeting: this.props.greeting};
    }
}
        

PropTypes on Steroids

Example #3: Redux Action types


type GreetingAction = {
    actionType: 'UPDATE_GREETING' | 'RESET_GREETING';
    payload: ?string;
}
            

// action creator
function updateGreeting(greeting: string): GreetingAction {
    return {
        // must be 'UPDATE_GREETING' or 'RESET_GREETING'
        actionType: 'UPDATE_GREETING',
        // must be a string or null/undefined
        payload: greeting
    };
}
            

Changes the way you write code

Allows for reliable refactoring (at least in WebStorm)

Catches errors before you even start your app