首页 文章

React中无状态函数与TypeScript错误:TS2352无法转换为'Promise<StatelessComponent<{}>>'类型

提问于
浏览
0

我是TypeScript的新手并拥有以下代码 .

import * as React from 'react';
const Product: React.SFC<{}> = () => <div>Product</div>;
export default Product;

import { asyncComponent } from 'react-async-component';

const AsyncProduct = asyncComponent({
  name: 'AsyncProduct',
  serverMode: 'resolve',
  resolve: () => {
    return import(/* webpackChunkName: "Product" */ './Product') as Promise<React.SFC<{}>>;
  },
});

export default AsyncProduct;

./src/AsyncProduct.tsx(7,12):错误TS2352:类型'Promise'无法转换为'Promise>'类型 . 类型'typeof“/ Users / banyan / tmp / typescript-react-async-component-example / src / Product”'与类型'StatelessComponent <{}>'不可比 . 输入'typeof“/ Users / banyan / tmp / typescript-react-async-component-example / src / Product”'不提供签名匹配'(props:{children?:ReactNode;},context?:any): ReactElement |空值' .

如果我将 Promise<React.SFC<{}> 更改为 Promise<any> ,则可以编译它,但是如何指定无状态函数?

这是使用 yarn start 重现的最小回购:https://github.com/banyan/typescript-react-async-component-example


类型的定义如下: node_modules/react-async-component/index.d.ts .

/**
 * The configuration for an asynchronous component.
 */
export interface Configuration<P> {
    resolve: () => Promise<React.ComponentType<P>>;
...
}

1 回答

  • 1

    import 函数返回整个模块,您必须从模块中选择您想要使用的内容(默认导出或命名导出):

    使用 async/await

    const AsyncProduct = asyncComponent({
      name: 'AsyncProduct',
      serverMode: 'resolve',
      resolve: async () => {
        var module = await import('./Product');
        return module.default;
      },
    });
    

    或者随后:

    const AsyncProduct2 = asyncComponent({
      name: 'AsyncProduct',
      serverMode: 'resolve',
      resolve: () => {
        return import('./Product').then(m=> m.default);
      },
    });
    

相关问题