小编典典

React重新构成道具上的Typescript错误

reactjs

我有一个非常基本的有状态组件,在其中我使用recompose将多个HOC添加到我的组件中(在我的示例中,为简单起见,我只使用了一个)。出于某种原因,打字稿给我关于我的道具进入组件的错误。如何摆脱这个错误?

这是我的代码:

import * as React from 'react';
import { connect } from 'react-redux';
import { compose } from 'recompose';

interface IStoreState {
  readonly sessionState: {
    authUser: { email: string; }
  }
}

interface IAccountPageProps { 
  authUser: { email: string } 
}

const AccountPage = ({ authUser }: IAccountPageProps ) =>
    <div>
      <h1>Account: {authUser.email}</h1>
    </div>

const mapStateToProps = (state: IStoreState) => ({
  authUser: state.sessionState.authUser,
});

export default compose(
  connect(mapStateToProps)
)(AccountPage);

我得到的错误是:

Argument of type '({ authUser }: IAccountPageProps) => Element' is not assignable to parameter of type 'ComponentType<{}>'.
  Type '({ authUser }: IAccountPageProps) => Element' is not assignable to type 'StatelessComponent<{}>'.
    Types of parameters '__0' and 'props' are incompatible.
      Type '{ children?: ReactNode; }' is not assignable to type 'IAccountPageProps'.
        Property 'authUser' is missing in type '{ children?: ReactNode; }'.

如果我不使用重组,而是写

export default connect(mapStateToProps)(AccountPage)

我没有任何错误。


阅读 360

收藏
2020-07-22

共1个答案

小编典典

通过compose的类型输入,您可以指定结果组件的类型以及可以调用的组件的类型,因此可以避免以下错误:

export default compose<IAccountPageProps, {}>(
  connect(mapStateToProps)
)(AccountPage);

不幸的是,compose不能确保类型安全或传递给它的功能的兼容性。

因此,例如,即使它显然无效,也不会产生键入错误:

export default compose<IAccountPageProps, {}>(
  connect(mapStateToProps),
  () => 'compose typing allows any function'
)(AccountPage);

嵌套HOC调用更安全:

export default 
connect(mapStateToProps)(
  firstHoc(
    secondHoc(
      AccountPage
    )
  )
);
2020-07-22