Currently, I am tackling a TypeScript project that involves Express.js. One of the areas I would like to enhance is the autocompletion and type support for custom headers when utilizing the res.setHeader()
method. Presented below is a condensed version of my code:
import * as express from "express"
export function traceIdMiddleware(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
if (req.headers["X-Trace-ID"]) {
const traceId = req.headers["X-Trace-ID"];
res.setHeader("X-Trace-ID", traceId);
}
// more logic...
next();
}
I am seeking guidance on how to extend the TypeScript Express interface in order to receive autocompletion and type validation for custom headers such as X-Trace-ID
when using res.setHeader()
.
In my attempt to extend Express.Response, I encountered challenges.
declare global {
namespace Express {
interface Response {
setHeader(field: 'X-Trace-ID', value: string): this;
}
}
}