React在道具上重构Causing Typescript错误

Jon*_*amb 3 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);
Run Code Online (Sandbox Code Playgroud)

而我得到的错误是:

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; }'.
Run Code Online (Sandbox Code Playgroud)

如果我不使用重构而改写

export default connect(mapStateToProps)(AccountPage)
Run Code Online (Sandbox Code Playgroud)

我没有得到任何错误.

Mat*_*hen 8

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

export default compose<IAccountPageProps, {}>(
  connect(mapStateToProps)
)(AccountPage);
Run Code Online (Sandbox Code Playgroud)

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


Bri*_*ams 5

compose 的类型允许您指定生成的组件的类型以及可以调用它的组件的类型,因此这将避免错误:

export default compose<IAccountPageProps, {}>(
  connect(mapStateToProps)
)(AccountPage);
Run Code Online (Sandbox Code Playgroud)

不幸的是,compose 没有做任何事情来确保传递给它的函数的类型安全或兼容性。

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

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

嵌套 HOC 调用更安全:

export default 
connect(mapStateToProps)(
  firstHoc(
    secondHoc(
      AccountPage
    )
  )
);
Run Code Online (Sandbox Code Playgroud)