如何在next.js中使用带有打字稿的express res.locals

我使用的快递-在我的应用next.js,我通过一些配置给客户端从服务器通过res.locals,我的项目是打字稿,我使用“@类型/下一个”:“^ 8.0。 6”。


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


预期答案: - 一种将“NextContext.res”或“NextResponse”覆盖为等于Express.res而不是的方法http.ServerResponse - 一种将 NextResponse 覆盖为 add 的方法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,

  }

}


慕桂英4014372
浏览 170回答 2
2回答

波斯汪

对于快速解决方案,这对我有用:&nbsp; &nbsp; import { Response } from 'express';&nbsp; &nbsp; MyDocument.getInitialProps = async (ctx) => {&nbsp; &nbsp; &nbsp; &nbsp; const { locals } = (ctx.res as Response);&nbsp; &nbsp; }

慕尼黑8549860

你总是可以像这样创建一个自定义界面:export interface Custom_Initial_Props extends Omit<NextPageContext, 'res'> {&nbsp; &nbsp; res: Express.Request;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript