流注入“任意”属性类型注释(来自mobx-react的“注入”)

时间:2019-05-29 11:03:50

标签: reactjs templates flowtype

我正在使用带有mobx-react作为商店提供者的流类型。 mobx-react使用创建HOC的实用程序功能为商店提供数据:

inject('a', 'b' ....)返回一个函数,该函数接受一个react组件,并返回一个设置了属性“ a”和“ b”的组件。

即:

type PropTy = {
    eventStore: EventStore; //or well somewhere else set
}

inject('eventStore')(class EventView extends React.Component<PropTy>) {
    render() {
        return <div>this.props.eventStore.length</div>
    }
}

我知道这不是100%安全的:没有办法确定“注入”(通过字符串)类型是否是实际类型。但是现在我希望忽略这一部分。我希望专注于使用上述组件。 -在我没有设置所有必需属性的情况下使用此组件流“投诉”的地方。 (由于我没有明确设置eventStore

因此,对于该类型,我尝试了以下操作:

inject: <Config: {}>(...args: Array<string>) =>
    ((React.AbstractComponent<Config>) =>
        React.AbstractComponent<$Diff<Config, args>>
    ),

但是,这在内部函数中带有流cannot resolve args的抱怨。 -我该怎么注释?

1 个答案:

答案 0 :(得分:0)

这是我能想到的:

import * as React from 'react';

declare function inject<Config: {}, InjectedConfig: {}>(
  ...args: Array<$Keys<InjectedConfig>>
): (React.AbstractComponent<Config> => React.AbstractComponent<$Diff<Config, InjectedConfig>>);

type FooProps = { a: number, b: string };
function Foo({ a, b }: FooProps) {
  return a + b;
}

type InjectedProps = { a: number };
const injectA = inject<FooProps, InjectedProps>('a');
const injectB = inject<FooProps, InjectedProps>('b'); // error

const Bar = injectA(Foo);

function App() {
  return (
    <>
      <Foo a={1} b="hi" />
      <Bar b="bye" />
      <Bar b={1} /> // error
    </>
  );
}

Try Flow

我注意到,如果您不将InjectedProps传递给inject,Flow不会总是推断出正确的事情。因此,我建议始终声明InjectedProps是什么,以确保Flow正确验证args和JSX参数。

Try Flow example,而没有InjectedProps