如何获得从 HOC 提供给它的 typecheck props 的流程?

How to get flow to typecheck props given to it from a HOC?

例如:

import { withProps } from 'recompose'

type Props = {
  name: string,
};

const NameTag = ({ name }: Props) => (
  <p style={{color: 'pink'}}>
    { name }
  </p>
);

const MyNameTag = withProps({
  // i want a error here
  name: 1
})(NameTag);

我如何得到无法将数字 1 传递给 NameTag 组件的道具 name 的错误?

谢谢。

至少 Flow 0.78 一使用 HOC 就会报错。

因此,如果您在代码中添加 <MyNameTag />,它应该会给您这个。

string [1] is incompatible with number [2] in property name of the first argument.

 [1]  7│   name: string,
      8│ };
      9│
     10│ const NameTag = ({ name }: Props) => (
     11│   <p style={{color: 'pink'}}>
     12│     { name }
     13│   </p>
       :
 [2] 19│   name: 1

这可能会发生,因为您在实例化 NameTag 时仍然可以通过 name,直到那时还不清楚它是否会失败。

流程复杂,我的流程很弱,不敢说这是流程bug

到目前为止,我发现捕获声明错误的唯一方法是构建一个 HOC,它只允许未被覆盖的属性,不允许其他任何东西。您将需要声明具有严格属性 {| a: string |} 的组件。检查这个例子:

// @flow

import * as React from 'react'


function myWithProps<
    MP, // My Properties. These are the pre-entered properties.
    CP, // Component properties. The properties originally expected by
        // the component.
    C: React.ComponentType<CP>, // The original component itself. Used to
                                // extract the properties template CP.
    IP: $Diff<CP, MP>, // Input properties. Properties that must be received
                       // by the HOC. We only expect the properties of the
                       // original component CP minus the properties MP that
                       // were specified when we created the HOC.
    >(myProps: MP): C => React.ComponentType<IP> {
        return component => props => <component {...myProps} {...props} />;
}


type Props = {|
  name: string,
  age: number,
|};


const NameTag = ({ name, age }: Props) => (
  <p style={{color: 'pink'}}>
    { name } { age }
  </p>
);


// $ExpectError. name has a wrong type.
const MyNameTag = myWithProps({name: 1})(NameTag);

// Should work.
const MyOtherNameTag = myWithProps({name: "hello"})(NameTag);

// Should work.
<MyOtherNameTag age={21} />;

// $ExpectError. name cannot be overriden.
<MyOtherNameTag age={21} name={"John"} />;

// $ExpectError. age has a wrong type.
<MyOtherNameTag age={"21"} />;

// $ExpectError. age missing.
<MyOtherNameTag />;

// $ExpectError. Unexpected parameter.
<MyOtherNameTag age={21} nmae={"John"} />;

myWithProps 使用通用类型,因此它应该适用于任何 class.

希望对您有所帮助!