gpt4 book ai didi

javascript - 使用可选属性扩展 TypeScript 类型

转载 作者:行者123 更新时间:2023-12-04 12:57:43 25 4
gpt4 key购买 nike

我正在使用 NextJS,需要扩展他们的 AppProps输入我自己添加的可选参数Layout .然而 AppProps类型由许多其他类型组成,例如
应用 Prop :

export declare type AppProps<P = {}> = AppPropsType<Router, P>;
应用 Prop 类型:
export declare type AppPropsType<R extends NextRouter = NextRouter, P = {}> = AppInitialProps & {
Component: NextComponentType<NextPageContext, any, P>;
router: R;
__N_SSG?: boolean;
__N_SSP?: boolean;
};
下一个组件类型:
export declare type NextComponentType<C extends BaseContext = NextPageContext, IP = {}, P = {}> = ComponentType<P> & {
/**
* Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.
* Make sure to return plain `Object` without using `Date`, `Map`, `Set`.
* @param ctx Context of `page`
*/
getInitialProps?(context: C): IP | Promise<IP>;
};
来自我的 _app.tsx我希望能够添加 LayoutComponent有类似的东西:
  Component: {
Layout?: React.FunctionComponent;
};
AppProps 有没有办法做到这一点?或者我需要扩展/相交 AppPropsType首先是 Layout然后重新声明我自己的 AppProps它使用扩展 AppPropsType ?

最佳答案

起初,我有这个丑陋的烂摊子来阻止错误:

import { AppProps } from 'next/app'    

export default function App({ Component, pageProps }: AppProps) {
const RedeclaredAndHacky_Component = Component as any
const Layout = RedeclaredAndHacky_Component.layoutProps?.Layout || Fr
/* Rest of the function */
}
我真的不喜欢这个,所以我最终得到了更接近你描述的东西:
import { NextComponentType, NextPageContext } from 'next'

type AppProps = {
pageProps: any
Component: NextComponentType<NextPageContext, any, {}> & { layoutProps: any }
}

export default function App({ Component, pageProps }: AppProps) {
const Layout = Component.layoutProps?.Layout || Shell
/* Rest of the function */
}

关于javascript - 使用可选属性扩展 TypeScript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64170731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com