2

TypeScript error when I'm trying to import one React component into another using React.lazy

templates/BugReport/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;

templates/Footer/index.tsx

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

I get a TypeScript error in Footer although I have default export in 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"

one note here I also have index.ts file in BugReport folder and error goes away when I remove that file but it needs to be there

Hayk Simonyan
  • 202
  • 4
  • 16

1 Answers1

6

I know that I`m late to answer, but maybe someone else have the same problem in the future like I just did and figured out by myself, but not before heading to this page and not finding any answer .

What is causing your problem

You are using Typescript without typing your function as a React Component.

React.lazy() expect a React Component as input.

As your function returns null and is not typed, React.Lazy can't know that it is a React Component.

The solution(s)

To solve this you could either:

Option 1 - change your return from null to a fragment like return <></>;, or

Option 2 - switch from function component to a Class component. As Clas components must have a render() method, it will be detected as a React Component even with a return null; or

Option 3 - switch to an arrow function and add a type to it, like React.FC or React.FunctionComponent. - const BugReport: FC = () => null;

For anyone in the future that got in here. At the point that I'm typing, for React.lazy() to work you SHOULD follow ONE of the three options mentioned above AND, as @Hayk said, your component MUST have a export default YourComponent.