typescript - 类型 'NextApiRequest' 缺少类型 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' 的以下属性

标签 typescript session next.js

下面的代码显示了 Next.js 项目中的一个错误。

Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Type 'NextApiRequest' is missing the following properties from type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>': get, header, accepts, acceptsCharsets, and 29 more.ts(2345)

import session from 'express-session'
import connectMongo from 'connect-mongo'

import type { NextApiRequest, NextApiResponse } from 'next'

const MongoStore = connectMongo(session)


export default function sessionMiddleware(req: NextApiRequest, res: NextApiResponse, next: any) {
  const mongoStore = new MongoStore({
    client: req.dbClient,
    stringify: false,
  })

  return session({
    secret: process.env.SESSION_SECRET ?? '',
    resave: false,
    saveUninitialized: false,
    store: mongoStore,
  })(req, res, next)
}

enter image description here

上述问题的任何解决方案。

最佳答案

Blockquote

我对这个问题的解决方案是使用联合类型 https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html

import { RequestHandler, Request, Response } from 'express';
import { NextApiRequest, NextApiResponse } from 'next';

type NextApiRequestWithFormData = NextApiRequest &
  Request & {
    files: any[];
  };

type NextApiResponseCustom = NextApiResponse & Response;

export default function initMiddleware(middleware: RequestHandler) {
  return (
    req: NextApiRequestWithFormData,
    res: NextApiResponseCustom
  ): Promise<any> =>
    new Promise((resolve, reject) => {
      middleware(req, res, (result: any) => {
        if (result instanceof Error) {
          return reject(result);
        }
        return resolve(result);
      });
    });
}

下面的代码应该适合你

import { RequestHandler, Request, Response } from 'express';
import { NextApiRequest, NextApiResponse } from 'next';

type NextApiRequestWithFormData = NextApiRequest &
  Request & {
    files: any[];
  };

type NextApiResponseCustom = NextApiResponse & Response;

关于typescript - 类型 'NextApiRequest' 缺少类型 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' 的以下属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68536004/

相关文章:

ngOnInit() 中的 Angular 4.x : How to load chance. js?

php - 在购物车 session 中添加新的

php - 在 Yii2 中自动登录多个域

node.js - 升级到Ionic 5后,TypeScript编译中缺少src/zone-flags.ts

html - Angular 2 形式 "Cannot Find Control"

angular - 如何读取配置文件以在打包为 WAR 并部署在 IBM Liberty 上的 Angular 应用程序中设置 API URL

c# - 在 session 中使用键/值集合

node.js - 找不到 Node 16.14.2 的模块 'worker_threads'

reactjs - 如何在我的react/nextjs应用程序的每个页面上显示购物车中的商品数量

javascript - 当我尝试使用 npm i 安装我的项目包时出现错误