【问题标题】:how to use express res.locals with typescript inside next.js如何在 next.js 中使用带有 typescript 的 express res.locals
【发布时间】:2019-12-13 08:26:32
【问题描述】:

我在我的应用程序中使用 express - next.js,我通过res.locals 将一些配置从服务器传递给客户端,我的项目在打字稿中,我使用“@types/next”:“ ^8.0.6"。

问题:打字稿说"Property 'locals' does not exist on type 'ServerResponse | Partial<ServerResponse>'."

预期答案: - 一种将“NextContext.res”或“NextResponse”覆盖为等于Express.res 而不是http.ServerResponse 的方法 - 一种覆盖 NextResponse 以添加 locals: any | {x:strong} 的方法。

这是我们所拥有的以及如何重现的简化示例:

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';

type Props = {
  locals: {};
}

export default class MyDocument extends Document<Props> {
  render() {
    const { locals } = this.props;

    return (
      <html>
        <Head>
          <ComponentUsingLocalsInfo locals={locals} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const { locals } = ctx.res;
  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    locals,
  }
}

【问题讨论】:

    标签: javascript reactjs typescript express


    【解决方案1】:

    对于一个快速的解决方案,这对我有用:

        import { Response } from 'express';
    
        MyDocument.getInitialProps = async (ctx) => {
    
            const { locals } = (ctx.res as Response);
    
        }
    

    【讨论】:

      【解决方案2】:

      您总是可以像这样创建自定义界面:

      export interface Custom_Initial_Props extends Omit<NextPageContext, 'res'> {
          res: Express.Request;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-30
        • 2023-01-24
        • 2020-10-01
        • 2019-04-27
        • 2022-01-22
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 2014-08-23
        相关资源
        最近更新 更多