反应重新构成导致打字机错误的道具 [英] React Recompose Causing Typescript Error On Props

查看:182
本文介绍了反应重新构成导致打字机错误的道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very basic stateful component where I'm using recompose to add multiple HOC to my component (in my example I only use one for simplicity). For some reason typescript is giving me an error regarding my props going into my component. How can I get rid of this error?

这是我的代码:

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而是写

If I don't use recompose and instead write

export default connect(mapStateToProps)(AccountPage)

我没有任何错误.

推荐答案

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

The typing for compose allows you to specify the type of the resulting component and the type of the component it can be called on, so this will avoid the errors:

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

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

Unfortunately, compose does nothing to ensure the type safety or compatibility of the functions handed to it.

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

So, for example, this won't generate a typing error even though it is obviously invalid:

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

嵌套HOC调用更安全:

It is safer to nest the HOC calls:

export default 
connect(mapStateToProps)(
  firstHoc(
    secondHoc(
      AccountPage
    )
  )
);

这篇关于反应重新构成导致打字机错误的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆