使用webpack输入问题进行反应和打字

jcr*_*898 9 typescript reactjs webpack

我正在尝试asyncComponent使用TypeScript 创建一个更高阶的组件,但不能完全正确地获得类型.

从本质上讲,这适用于JS与webpack ...

const Auth = asyncComponent(() =>
  require.ensure([], require => require("../auth/index").default, "auth_async"),
);
Run Code Online (Sandbox Code Playgroud)

asyncComponent是一个更高阶的函数,执行以下操作...

import * as React from "react";
import { Component } from 'react';

export interface IAsyncComponentProps {}

export interface IAsyncComponentState {
  Component: typeof Component
}

interface IGetComponent {
  (): Promise<typeof Component>;
}

export default function asyncComponent (getComponent: IGetComponent) {
  let ComponentCache: typeof Component = null;

  return class AsyncComponent extends Component<IAsyncComponentProps, IAsyncComponentState> {
    state: {
      Component: typeof Component,
    };

    constructor(props: IAsyncComponentProps) {
      super(props);
      this.state = { Component: ComponentCache };
    }

    componentWillMount() {
      if (!this.state.Component) {
        getComponent().then((Component) => {
          ComponentCache = Component;

          this.setState({ Component });
        });
      }
    }
    render() {
      const { Component } = this.state;

      if (Component) {
        return <Component {...this.props} />;
      }
      return null;
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

但是,编译时我收到错误...

src/components/asyncComponent/index.tsx(40,27): error TS2322: Type '{ children?: ReactNode; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<P, S>> & Readonly<{ children?: ReactNode...'.
  Type '{ children?: ReactNode; }' is not assignable to type 'Readonly<P>'.
src/index.ts(3,7): error TS1141: String literal expected.
11:06:50 AM - Compilation complete. Watching for file changes.
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

bas*_*rat 2

您的示例在最新的 TypeScript 中编译良好,没有错误:

在此输入图像描述

更多的

  • 更新至typescript@next