首页 > 解决方案 > React Recompose 在 Props 上导致 Typescript 错误

问题描述

我有一个非常基本的有状态组件,我使用 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; }'.

如果我不使用 recompose 而是写

export default connect(mapStateToProps)(AccountPage)

我没有收到任何错误。

标签: reactjstypescriptrecompose

解决方案


当前的打字compose是非常没用的。如果要使用compose,则必须props手动指定原始组件和最终组件的类型,并且不会检查您指定的类型是否与您传递的高阶组件列表匹配:

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

我建议不要compose在 TypeScript 中使用。


推荐阅读