我正在学习打字稿,但我似乎无法弄清楚如何正确键入我的无状态组件,这些组件都具有redux HOC,可以为它们注入一些道具和功能。
这是我的wrapper.tsx
export type Props = ReturnType<typeof mapStateToProps> &
ReturnType<typeof mapDispatchToProps> & {
fetchMorePosts: () => void;
};
const withPostFeedWrapper = <WrapperProps extends Props>(
WrappedComponent: React.FunctionComponent<WrapperProps>
) => {
const PostFeed: React.FunctionComponent<Props> = (props) => {
const { postFeed, fetchPostFeed } = props;
useEffect(() => {
fetchPostFeed({
offset: postFeed.offset,
limit: postFeed.limit,
});
}, [fetchPostFeed])
const fetchMorePosts = useCallback(() => {
...do stuff
}, []);
return (
<WrappedComponent
{...props as WrapperProps}
fetchMorePosts={fetchMorePosts}
/>
);
};
return connect<
ReturnType<typeof mapStateToProps>,
ReturnType<typeof mapDispatchToProps>,
Props,
State
>(
mapStateToProps,
mapDispatchToProps
)(PostFeed);
};
const mapStateToProps = (state: State) => ({
postFeed: state.postFeed,
});
const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
return {
fetchPostFeed: (variables: FetchPostFeedPostsVariables) =>
dispatch(fetchPostFeed(variables)),
dispatch,
};
};
export default withPostFeedWrapper;
这是我的孩子部分
import withPostFeedWrapper, { Props } from "./wrapper";
const PostFeed: React.FunctionComponent<Props> = ({
postFeed,
fetchMorePosts,
}) => {
return (
<>
...stuff
</>
);
};
export default withPostFeedWrapper(PostFeed)
当我这样导入时,它会出错
import PostFeed from "containers/_post-feed";
const Homepage: React.FunctionComponent<HomepageProps> = ({
...props
}) => {
return (
<div className="homepage">
<PostFeed />
</div>
);
};
这是错误
import PostFeed
Property 'fetchMorePosts' is missing in type '{}' but required in type 'Pick<Props, "fetchMorePosts">'.ts(2741)
wrapper.tsx(21, 5): 'fetchMorePosts' is declared here.
该组件应该工作的方式,在将其导入另一个文件时,我不需要传递props
。 HOC应该注意这一点。这段代码可以正常运行,只有打字稿出错了。
我想念什么?
答案 0 :(得分:0)
由于包装的组件不需要传递fetchMorePosts
,因此应将其键入为React.FunctionComponent<Omit<Props, 'fetchMorePosts'>>
(该组件需要与Props
中的props相同,只是没有{{1} })
您还可以从'fetchMorePosts'
推断中省略显式类型参数,它将很好地工作(并且您传入的类型参数是错误的,connect
类型参数已添加到结果组件所需的props中)
TOwnProps