You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js布局default导出类型错误:Props类型无效求助

Next.js Layout组件类型错误分析

执行yarn build时出现如下编译错误:

- info Compiled successfully
- info Linting and checking validity of types ...Failed to compile.

app/[prefName]/create/layout.tsx
Type error: Layout "app/[prefName]/create/layout.tsx" has an invalid "default" export:
  Type "Props" is not valid.

问题代码片段

app/[prefName]/create/layout.tsx:

import type { Metadata } from "next";
import { lookupPrefecture } from "@/config/prefectures";

type Props = {
  children: React.ReactNode;
  params: { prefName: string };
  searchParams: { [key: string]: string | string[] | undefined };
};

export async function generateMetadata(
  { params, searchParams }: Props,
): Promise<Metadata> {
  // read route params
  const { prefName } = params;
  const encodedPrefName = decodeURIComponent(prefName);
  const prefectureName = lookupPrefecture(encodedPrefName);

  return {
    title: `${prefectureName} | Create Post`,
    openGraph: {
      images: ["/some-specific-page-image.jpg"],
    },
  };
}

export default function CreateLayout({ children, params, searchParams }: Props) {
  return (
    <> {children} </>
  );
}

类型检查报错详情

Type 'OmitWithTag<Props, keyof LayoutProps, "generateMetadata">' does not satisfy the constraint '{ [x: string]: never; }'.
  
Property 'searchParams' is incompatible with index signature.
    
Type '{ [key: string]: string | string[] | undefined; }' is not assignable to type 'never'.ts(2344)
type Diff<Base, T extends Base, Message extends string = ""> = 0 extends 1 & T ? {} : OmitWithTag<T, keyof Base, Message>

问题原因

Next.js App Router规范中,Layout组件的默认导出函数不接收searchParams作为props。Layout组件的合法props仅包含children和params,而你定义的Props类型中额外添加了searchParams,导致与Next.js内置的LayoutProps类型不匹配,触发类型检查错误。

注意:searchParams可以在generateMetadata、generateStaticParams以及Page组件的props中正常使用,但Layout组件本身不支持该参数。

解决方案

  1. 修改Props类型,移除searchParams字段:
type LayoutProps = {
  children: React.ReactNode;
  params: { prefName: string };
};
  1. 调整Layout组件的参数,去掉searchParams:
export default function CreateLayout({ children, params }: LayoutProps) {
  return (
    <> {children} </>
  );
}
  1. 若generateMetadata仍需使用searchParams,单独为其定义参数类型:
type MetadataProps = LayoutProps & {
  searchParams: { [key: string]: string | string[] | undefined };
};

export async function generateMetadata(
  { params, searchParams }: MetadataProps,
): Promise<Metadata> {
  // 原有逻辑保持不变
}

内容的提问来源于stack exchange,提问作者kawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:24:50