如何在React.CreateClass中为对象属性提供流类型提示

时间:2016-11-17 15:25:23

标签: javascript reactjs flowtype

我有一些使用React.createClass创建的组件的React代码。

某些组件将对象存储为对象作为常规属性,例如this.foo而不是this.props.foothis.state.foo

有没有办法提供关于'foo'属性的Flow的提示?我现在想避免重写这些组件。

1 个答案:

答案 0 :(得分:1)

您可以为传递给createClass的对象提供显式类型。像

这样的东西
/* @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);

或者如果您希望保持内联类型,只需使用强制转换

/* @flow */

import React from 'react';

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

要证明这一点,请尝试将foo设为42。 Flow会抱怨

/* @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 }));