我以为我已经找到了一种无需全局声明即可创建 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();
};
您可以尝试创建一个接口来扩展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