首页 > 解决方案 > 类型'typeof import(“...”)'中缺少属性'default',但类型'{默认值:ComponentType; }'

问题描述

当我尝试使用将一个 React 组件导入另一个组件时出现 TypeScript 错误React.lazy

模板/错误报告/index.tsx

import { useEffect, useContext } from 'react';
import BugReportStatic from '@tamm/ui-lib-v2-bug-report';
import baseUrl from 'client/utils/baseUrl';
import { StoreContext } from 'client/services/context';

function BugReport() {
  const store = useContext(StoreContext);
  useEffect(() => {
    BugReportStatic.init({
      bugReportIntegrationApi: `${baseUrl}/pub/feedback/bugReport`,
      store,
      isStore: !!store,
    });
    return () => {
      BugReportStatic.destroy();
    };
  }, []);
  return null;
}

export default BugReport;

模板/页脚/index.tsx

const BugReport = lazy(() =>
  import(/* webpackChunkName: "bug-report" */ 'client/templates/BugReport'),
);

Footer尽管我有默认导出,但我收到 TypeScript 错误BugReport

Type 'Promise<typeof import("/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Property 'default' is missing in type 'typeof import("/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index")' but required in type '{ default: ComponentType<any>; }'.ts(2322)
index.d.ts(789, 34): 'default' is declared here.
index.d.ts(789, 18): The expected type comes from the return type of this signature.
module "/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index"

这里有一个注意事项,我index.ts在 BugReport 文件夹中也有文件,当我删除该文件时错误消失了,但它需要在那里

标签: reactjstypescriptimportreact-typescriptreact-lazy-load

解决方案


我知道我回答迟了,但也许其他人将来会遇到同样的问题,就像我刚刚做的一样并且自己想通了,但在前往此页面并没有找到任何答案之前。

是什么导致了您的问题

您正在使用 Typescript,但没有将您的函数输入为 React 组件。

React.lazy() 期望一个 React 组件作为输入。

由于您的函数返回 null 并且未键入,因此 React.Lazy 无法知道它是 React 组件。

解决方案

要解决此问题,您可以:

选项 1 -将您的返回值从 null 更改为类似的片段return <></>;,或

选项 2 -从功能组件切换到类组件。由于 Clas 组件必须有一个render()方法,因此即使带有return null;or也会被检测为 React 组件

选项 3 - 切换到箭头函数并向其添加类型,例如 React.FC 或 React.FunctionComponent。-const BugReport: FC = () => null;

对于未来进入这里的任何人。在我输入的时候,为了让 React.lazy() 工作,你应该遵循上面提到的三个选项之一,并且正如@Hayk 所说,你的组件必须有一个export default YourComponent.


推荐阅读