您可以通过将getLayout
属性添加到AppProps.Component
.
next.d.ts
(从 Next 11.1.0 开始):
import type { CompletePrivateRouteInfo } from 'next/dist/shared/lib/router/router';
import type { Router } from 'next/dist/client/router';
declare module 'next/app' {
export declare type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {
router: Router;
} & Record<string, any> & {
Component: {
getLayout?: (page: JSX.Element) => JSX.Element;
}
}
}
pages/_app.tsx
:
import type { AppProps } from 'next/app';
const NextApp = ({ Component, pageProps }: AppProps) => {
// Typescript does not complain about unknown property
const getLayout = Component.getLayout || ((page) => page);
// snip
}
如果你想要更多的类型安全,你可以定义自定义NextPageWithLayout
类型,它会断言你的组件有getLayout
属性集。
next.d.ts
(从 Next 11.1.0 开始):
import type { NextPage } from 'next';
import type { NextComponentType } from 'next/dist/next-server/lib/utils';
declare module 'next' {
export declare type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
getLayout: (component: NextComponentType) => JSX.Element;
};
}
pages/example-page/index.tsx
:
import type { NextPageWithLayout } from 'next';
const ExamplePage: NextPageWithLayout<ExamplePageProps> = () => {
// snip
}
// If you won't define `getLayout` property on this component, TypeScript will complain
ExamplePage.getLayout = (page) => {
// snip
}
请注意,在扩展 Next 类型定义时,您必须提供准确的类型/接口签名(以及匹配的泛型),否则声明合并将不起作用。不幸的是,如果库更改 API,这意味着调整类型定义。