te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Extending a TypeScript Type with an optional property - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extending a TypeScript Type with an optional property - Stack Overflow

programmeradmin1浏览0评论

I am working with NextJS and need to extend their AppProps type with an optional parameter that I have added myself Layout. However the AppProps type is made up of many others e.g.

AppProps:

export declare type AppProps<P = {}> = AppPropsType<Router, P>;

AppPropsType:

export declare type AppPropsType<R extends NextRouter = NextRouter, P = {}> = AppInitialProps & {
    Component: NextComponentType<NextPageContext, any, P>;
    router: R;
    __N_SSG?: boolean;
    __N_SSP?: boolean;
};

NextComponentType:

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>;
};

From my _app.tsx I want to be able to add Layout to Component with something like:

  Component: {
    Layout?: React.FunctionComponent;
  };

Is there a way to do this from AppProps or would I need to extend/intersect AppPropsType first with Layout then redeclare my own AppProps which uses the extended AppPropsType?

I am working with NextJS and need to extend their AppProps type with an optional parameter that I have added myself Layout. However the AppProps type is made up of many others e.g.

AppProps:

export declare type AppProps<P = {}> = AppPropsType<Router, P>;

AppPropsType:

export declare type AppPropsType<R extends NextRouter = NextRouter, P = {}> = AppInitialProps & {
    Component: NextComponentType<NextPageContext, any, P>;
    router: R;
    __N_SSG?: boolean;
    __N_SSP?: boolean;
};

NextComponentType:

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>;
};

From my _app.tsx I want to be able to add Layout to Component with something like:

  Component: {
    Layout?: React.FunctionComponent;
  };

Is there a way to do this from AppProps or would I need to extend/intersect AppPropsType first with Layout then redeclare my own AppProps which uses the extended AppPropsType?

Share Improve this question asked Oct 2, 2020 at 11:25 RyanP13RyanP13 7,75328 gold badges101 silver badges170 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

I create a custom AppProps Next type so that way I can edit the Component type.

interface CustomAppProps extends Omit<AppProps, "Component"> {
  Component: AppProps["Component"] & { Layout: JSX.Element };
}

The final result will look something like this:

import type { AppProps } from "next/app";

interface CustomAppProps extends Omit<AppProps, "Component"> {
  Component: AppProps["Component"] & { Layout: JSX.Element };
}

function CustomApp({ Component, pageProps }: CustomAppProps) {
  return <Component {...pageProps} />;
}

export default CustomApp;

At first, I had this ugly mess to stop errors:

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 */
}

I didn't really like this, so I ended up with something closer to what you described:

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 */
}

I've modified a little bit the answer of Pablo Verduzco. I think is more readable and extensible.

import type { AppProps } from "next/app"

interface CustomAppProps {
  Component: AppProps["Component"] & {
    auth: {
      role: string
    }
  }
  pageProps: AppProps["pageProps"]
}

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

export default MyApp;

In the material-ui examples there is some code which may help readers of this question as well: https://github./mui/material-ui/blob/3c528113f47cfddf2504ea02ba3065e7c5c46928/examples/nextjs-with-typescript/pages/_app.tsx#L13-L15

import * as React from 'react';
import Head from 'next/head';
import { AppProps } from 'next/app';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider, EmotionCache } from '@emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

interface MyAppProps extends AppProps {
  emotionCache?: EmotionCache;
}

export default function MyApp(props: MyAppProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  );
}

发布评论

评论列表(0)

  1. 暂无评论