codememo

NextJS _app.tsx 컴포넌트 및 pageProps의 TypeScript 유형을 선택합니다.

tipmemo 2023. 4. 3. 21:32
반응형

NextJS _app.tsx 컴포넌트 및 pageProps의 TypeScript 유형을 선택합니다.

NextJS의 기본 _app.tsx는 다음과 같습니다.

function MyApp({ Component, pageProps }) {
  return (
    <Component {...pageProps} />
  )
}

문제는 TypeScript로 전환하자마자 ES6Lint 아래에 이러한 유형이 본질적으로 '임의'로 설정되어 있다는 경고가 표시된다는 것입니다.단, 이 두 가지 타입을 어떤 타입으로 설정하면 나중에 미스매치가 발생할지 알 수 없습니다.이 두 가지를 어떤 타입으로 캐스팅해야 합니까?

빌트인AppPropstype이 범용이 되었습니다.커스텀을 사용하려면PageProps에 전달하다AppProps입력:

import { AppProps } from 'next/app';

interface CustomPageProps { // <--- your custom page props
   // your props
}

function MyApp({ Component, pageProps }: AppProps<CustomPageProps>) {
                                             //   ^^^ use your custom props here
  return <Component {...pageProps} />
                    // ^^^^^ pageProps is now typeof CustomPageProps
}

최신 솔루션:다음 JSAppProps

next.js 버전12.3.0 에서는 범용이 에 전달됩니다.AppProps로 넘어갈 것이다pageProps(관련 PR 참조).아래의 예를 참조해 주세요.

// importing the provided NextJS type
import type { AppProps } from "next/app";

// use the type and pass it your page props type
export default function App({
  Component,
  pageProps,
}: AppProps<CustomPageProps>) {
  //...
}

이전 솔루션(next.js 12.3.0 이전):

개선된AppProps커스터마이즈할 수 있도록 하다pageProps

다음 JS는AppPropsImport하여 사용할 수 있는 상자에서 꺼내서_app요소.그러면 요청하신 유형이 제공됩니다.단, 이 타입은pageProps디폴트 타입으로 변경해 주세요.이것은, 원하는 타입이 아닐 수 있습니다.

이걸 좀 더 통제하고 싶다면AppPropstype 인수를 사용하지만, 그 인수는 에 한정됩니다.Component,떠나는pageProps어떤 일이 있어도 그런 타입으로.

이 문제를 해결할 수 있습니다.AppProps타입 인수를 실제로 건네주는 타입pageProps뿐만 아니라.아래의 작업 예를 참조하십시오.

_app.tsx

// importing the provided NextJS type
import type { AppProps as NextAppProps } from "next/app";

// modified version - allows for custom pageProps type, falling back to 'any'
type AppProps<P = any> = {
  pageProps: P;
} & Omit<NextAppProps<P>, "pageProps">;

// use the new type like so, replacing 'CustomPageProps' with whatever you want
export default function App({
  Component,
  pageProps,
}: AppProps<CustomPageProps>) {
  //...
}

'함수가 반환 유형 누락' 경고가 계속 표시되면 반환 유형 JSX를 추가하십시오.요소

import { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps): JSX.Element {
  return <Component {...pageProps} />
}

필요한 경우err오브젝트도:

export default function App({
  Component,
  pageProps,
  err,
}: AppProps & { err: any }) {
  // Workaround for https://github.com/vercel/next.js/issues/8592
  return <Component {...pageProps} err={err} />
}

제 생각에 당신은 다른 사람들을 따라잡을 수 있는 타입이 필요할 것 같아요.getInitialProps뿐만 아니라.여기 있습니다.

type Props<P> = AppProps & P;

interface AppType<P> {
  (props: Props<P>): ReactElement;
  getInitialProps?: (context: AppContext) => Props<P> | Promise<Props<P>>;
}

문서: https://nextjs.org/docs/basic-features/typescript#custom-app

import type { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

언급URL : https://stackoverflow.com/questions/64722812/what-typescript-type-should-nextjs-app-tsx-component-and-pageprops-be

반응형