带有React Lazy的TypeScript出现Promise错误

时间:2019-05-04 12:44:56

标签: reactjs typescript react-router higher-order-components

我正在使用带有打字稿的react.I使用了更高阶的组件来检查用户是否通过身份验证。添加专案后,我在以下路线中得到错误

 /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/remsys/src/navigation/routes.ts
TypeScript error in /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/remsys/src/navigation/routes.ts(7,36):
Type 'Promise<typeof import("/home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/remsys/src/pages/Secure/Dashboard/index")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Type 'typeof import("/home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/remsys/src/pages/Secure/Dashboard/index")' is not assignable to type '{ default: ComponentType<any>; }'.
    Types of property 'default' are incompatible.
      Type '{}' is not assignable to type 'ComponentType<any>'.
        Type '{}' is not assignable to type 'FunctionComponent<any>'.
          Type '{}' provides no match for the signature '(props: any, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.  TS2322

     5 | export const SignIn = React.lazy(() => import('pages/Public/SignIn'));
     6 | 
  >  7 | const Dashboard = React.lazy(() => import('pages/Secure/Dashboard'));
       |                                    ^
     8 | 
     9 | const routes = [{ path: '/dashboard', exact: true, name: 'Dashboard', component: Dashboard }];
    10 |

Routes.ts

   export const DefaultLayout = React.lazy(() => import('../containers/DefaultLayout'));

const Dashboard = React.lazy(() => import('../pages/Secure/Dashboard'));

const routes = [{ path: '/dashboard', exact: true, name: 'Dashboard', component: Dashboard }];

export default routes;

HOC:

interface HocProps {
  authUser: AuthToken;
  history?: any;
}


const withAuthentication = () => (Component: any) => {
  class WithAuthentication extends React.Component<HocProps, {}> {
    componentDidMount() {
      if (isEmpty(this.props.authUser)) {
        this.props.history.push('/signin');
      }
    }

    render() {      
      return this.props.authUser ? <Component {...this.props} /> : null;
    }
  }

  function mapStateToProps() {
    return {
      authUser: getAuthHeaders()
    };
  }

  return compose(
    withRouter,
    connect(mapStateToProps)
  )(WithAuthentication);
};

export default withAuthentication;

Dashboard.tsx:

const Dashboard = () => <div>Dashboard</div>;

export default compose(
    withAuthentication(),
    connect(null)
)(Dashboard);

由于我是打字稿新手,所以我无法弄清楚是什么错误

1 个答案:

答案 0 :(得分:2)

我只能认为是由于Dashboard的默认导出类型为{}(从compose函数返回)而与React组件签名不匹配而导致的。

尝试将Dashboard中的导出行更改为:

export default compose(
    withAuthentication(),
    connect(null)
)(Dashboard) as React.ComponentType<any>;

这将强制将导出强制转换为正确的类型,从而使React.lazy正常工作。