wmil wmil - 17 days ago 6
React JSX Question

How to provide flowtype hints in React.CreateClass for object properties

I have some React code that uses components created with React.createClass.

Some of the components store things on the object as normal properties, e.g.

this.foo
as opposed to
this.props.foo
or
this.state.foo
.

Is there any way to provide a hint to Flow about the 'foo' property? I'd like to avoid rewriting these components for now.

Answer

You could provide an explicit type to the object passed to createClass. Something like

/* @flow */

import React from 'react';

type Spec = { foo: string };

const spec: Spec = {
  foo: 'bar',
  render() {
    return <div>{this.foo}</div>;
  }
}

const MyComponent = React.createClass(spec);

or if you prefer keeping the types inline, just use a cast

/* @flow */

import React from 'react';

const MyComponent = React.createClass(({
  foo: 'bar',
  render() {
    return <div>{this.foo}</div>;
  }
}: { foo: string }));

To prove this works, try setting foo to 42. Flow will complain

/* @flow */

import React from 'react';

const MyComponent = React.createClass(({
  foo: 42, // <-- error: number. This type is incompatible with string
  render() {
    return <div>{this.foo}</div>;
  }
}: { foo: string }));
Comments