【问题标题】:Flow inject "arbitrary" properties type annotation ('inject' from mobx-react)流注入“任意”属性类型注释(来自 mobx-react 的“注入”)
【发布时间】:2019-05-29 23:44:43
【问题描述】:

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

inject('a', 'b' ....) 返回一个函数,该函数接受一个反应组件并返回一个设置了属性“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 抱怨。 - 我将如何注释这个?

【问题讨论】:

    标签: reactjs templates flowtype


    【解决方案1】:

    这是我能想到的:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2019-09-01
      • 2015-07-03
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多