我正在使用mobx-react作为商店的提供者的流类型。mobx-react使用创建HOC的实用程序函数提供store dat:
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>>
),然而,这与内部函数处的flow cannot resolve args有关。-我该如何对其进行注释?
发布于 2019-05-29 23:44:44
这是我能想到的:
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
</>
);
}我注意到,如果不将InjectedProps传递给inject,Flow不会总是推断出正确的事情。因此,我建议始终声明什么是InjectedProps,以确保Flow正确地验证args和JSX参数。
不带InjectedProps的Try Flow example。
https://stackoverflow.com/questions/56359073
复制相似问题