I thought I had found a way to create the properties of a Request object without the need for global declarations, but a problem arose.
I tried to use the generic Locals for Request to create the req.auth property, but it returned an error and now I have a question about what this generic is needed for. Here is an example:
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();
};
You can try to create a interface to extends Request instead of passing the interface to Request.
interface Local extends Request {
auth: {
token: string;
payload: Object;
};
}
const example = function (req: Local, res: Response, next: NextFunction) {
req.auth;
next();
};
If you hover the Request
type, you can see that the fifth type is Locals extends Record<string, any>
which this type will be used for res.locals
, not req