Next.js Dynamic Import를 TypeScript에서 사용할 시의 타입 오류
오류 내용
1Argument of type '() => Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((props: PageProps) => JSX.Element)>' is not assignable to parameter of type 'DynamicOptions<{}> | (() => LoaderComponent<{}>) | LoaderComponent<{}>'.2 Type '() => Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((props: PageProps) => JSX.Element)>' is not assignable to type '() => LoaderComponent<{}>'.3 Type 'Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((props: PageProps) => Element)>' is not assignable to type 'LoaderComponent<{}>'.4 Type 'ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((props: PageProps) => Element)' is not assignable to type 'ComponentClass<{}, any> | FunctionComponent<{}> | { default: ComponentType<{}>; }'.5 Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any> | FunctionComponent<{}> | { default: ComponentType<{}>; }'.6 Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any>'.7 Types of property 'getDerivedStateFromProps' are incompatible.8 Type 'GetDerivedStateFromProps<never, any> | undefined' is not assignable to type 'GetDerivedStateFromProps<{}, any> | undefined'.9 Type 'GetDerivedStateFromProps<never, any>' is not assignable to type 'GetDerivedStateFromProps<{}, any>'.10 Types of parameters 'nextProps' and 'nextProps' are incompatible.11 Type 'Readonly<{}>' is not assignable to type 'never'.
Next.js의 Dynamic Import 기능을 TypeScript와 함께 사용할 때의 오류.
오류 코드
1import dynamic from "next/dynamic";2const Named = dynamic(() => import("./Named").then(module => module.Named));
해결법
1const MyComponent = dynamic<PropsType>(() =>2 import("./Named").then(module => module.Named)3);
dynamic
에 컴포넌트의 Props을 넣어주어야 한다.
1export const Named = ({ propItem }: PropsType) => {2 return <span>{propItem}</span>;3}
그럼 자식 컴포넌트인 Named는 이렇게 작성해주면 되겠다.
만약, Props가 없는 경우엔?
{}
타입을 쓰면 된다.
만약, typescript-eslint가 ban-types 룰 오류를 낸다면 다음 깃헙 이슈의 코멘트를 참고하자.
여담
이런 중요한 걸 도큐멘트에 넣어야하지 않을까. 이걸 왜 직접 찾아보게 만드는지.
어쨋든... 다음 이슈에서 해결법을 찾았다.