React Recompose Causing Typescript Error On Props

£可爱£侵袭症+ 提交于 2019-11-29 11:57:30

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);

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);

It is safer to nest the HOC calls:

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

The current typing of compose is pretty useless. If you want to use compose, you have to specify the props type of the original and final components manually, and there is no checking that the types you specified match the list of higher-order components you passed:

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

I'd recommend not using compose in TypeScript.

The best solution I've found is to re-assert the type so that you get connect's typings too (including .WrappedComponent which can be used for easy testing), else it defaults to an React.ComponentClass<{}, any> which is incorrect and gives you no information about the component as per @Matt's example above.

Using your example see:

import React, { SFC } from 'react';
import { connect, ConnectedComponentClass } from 'react-redux';

export default compose<IAccountPageProps, {}>(
  connect(mapStateToProps)
)(AccountPage) as ConnectedComponentClass<SFC<IAccountPageProps>, {}>

Now the returned component has the correct typing to the connect wrapper as ConnectedComponentClass<React.StatelessComponent<IAccountPageProps>, {}> when you go to use the component elsewhere, and now you can also access connectedComponent values such as .WrappedComponent.

ConnectedComponentClass is react-redux's typing for it's end type of a connected component. In a perfect world this shouldn't be necessary, but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!