Next.js中FC<WrapperProps>无layout/otherProps属性的TypeScript错误解决
Next.js 多布局实现中的TypeScript类型错误解决
错误信息
Property 'layout' does not exist on type 'FC<WrapperProps>'. Property 'otherProps' does not exist on type 'FC<WrapperProps>'
相关代码
_app.tsx
import Layout from '@/components/layouts' import NoLayout from '@/components/layouts/NoLayout' import '@/styles/globals.css' import { Nunito } from 'next/font/google' import type { AppProps } from 'next/app' import { CompProps, WrapperProps } from '@/lib/utils' const layouts: Record<string, React.FC<WrapperProps>> = { L1: Layout, L2: NoLayout, }; interface CustomAppProps extends AppProps { Component: React.FC<CompProps>; } export default function App({ Component, pageProps }: CustomAppProps) { const SelectedLayout = layouts[Component.layout || 'L1'] || (({ children }) => <>{children}</>); return ( <div className={nunito.className}> <SelectedLayout> <Component {...pageProps} otherProps={Component.otherProps} /> </SelectedLayout> </div> ); }
utils.ts
export type CompProps = { footer?: boolean; style?: string; layout?: string; } export interface WrapperProps { children: React.ReactNode; otherProps?: CompProps; }
解决方法
错误根源是React.FC基础类型不包含你自定义的layout、otherProps静态属性,需要扩展组件类型定义来兼容这些属性:
- 修改utils.ts,添加带静态属性的组件类型
import type { FC } from 'react'; export type CompProps = { footer?: boolean; style?: string; layout?: string; } export interface WrapperProps { children: React.ReactNode; otherProps?: CompProps; } // 定义带有静态属性的页面组件类型 export type PageComponent = FC<CompProps> & { layout?: string; otherProps?: CompProps; };
- 更新_app.tsx中的组件类型引用
import Layout from '@/components/layouts' import NoLayout from '@/components/layouts/NoLayout' import '@/styles/globals.css' import { Nunito } from 'next/font/google' import type { AppProps } from 'next/app' import { CompProps, WrapperProps, PageComponent } from '@/lib/utils' // 补充Nunito字体初始化(原代码遗漏) const nunito = Nunito({ subsets: ['latin'] }) const layouts: Record<string, React.FC<WrapperProps>> = { L1: Layout, L2: NoLayout, }; interface CustomAppProps extends AppProps { Component: PageComponent; // 使用扩展后的组件类型 } export default function App({ Component, pageProps }: CustomAppProps) { const SelectedLayout = layouts[Component.layout || 'L1'] || (({ children }) => <>{children}</>); return ( <div className={nunito.className}> <SelectedLayout> <Component {...pageProps} otherProps={Component.otherProps} /> </SelectedLayout> </div> ); }
说明
React.FC仅定义函数组件的props结构,默认不包含静态属性,通过&交叉类型可以给基础组件类型追加静态属性的定义。- 补充了Nunito字体的初始化代码,避免运行时出现
nunito未定义的报错。
内容的提问来源于stack exchange,提问作者HaryanviDeveloper
相关产品推荐
相关产品推荐

