为什么我需要一个通用的 Locals 类型的 Express 请求?

问题描述 投票:0回答:1

我以为我已经找到了一种无需全局声明即可创建 Request 对象属性的方法,但是出现了问题。

我尝试使用通用的 Locals for Request 来创建 req.auth 属性,但它返回了一个错误,现在我有一个关于这个通用的用途的问题。这是一个例子:

import { Request, Response, NextFunction } from "express";

interface Local {
  auth: {
    token: string;
    payload: Object;
  }
}

const example = function (req: Request<{}, {}, {}, {}, Local>, res: Response, next: NextFunction) {
  req.auth
  next();
};
typescript express backend
1个回答
0
投票

您可以尝试创建一个接口来扩展Request,而不是将接口传递给Request。

interface Local extends Request {
  auth: {
    token: string;
    payload: Object;
  };
}


const example = function (req: Local, res: Response, next: NextFunction) {
  req.auth;
  next();
};

如果将鼠标悬停在

Request
类型上,您可以看到第五种类型是
Locals extends Record<string, any>
,该类型将用于
res.locals
,而不是
req

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.