While reading the TypeScript documentation, I came across type assertions but it seems they are limited to expressions only. I am looking to assert the type of a variable on the left side of an assignment statement.
My specific scenario involves an Express middleware that adds a user
property to the req
object:
app.use(async (req, res, next) => {
// ...
req.user = user; // Property 'user' does not exist on type 'Request'.
// ...
});
I am aware that I can simply reassign the variable, but that approach feels a bit clunky:
interface AuthenticationRequest extends Request {
user: string;
}
const myReq = <AuthenticationRequest>req;
myReq = user;
Is there a more elegant solution to this issue?