The TypeScript docs talk about type assertions, but apparently they can only be used in expressions, while I'd need to assert the type of a variable on the left hand side of an assignment.

My specific situation is an express middleware that extends the req object with a user property:

app.use(async (req, res, next) => {
  // ...
  req.user = user; // Property 'user' does not exist on type 'Request'.
  // ...
});

I know that I can just reassign the variable, but that seems a little clumsy:

interface AuthenticationRequest extends Request {
    user: string;
}

const myReq = <AuthenticationRequest>req;

myReq = user;

Is there a more elegant way?

1 Answers

1
Titian Cernicova-Dragomir On Best Solutions

You can have a type assertion on the left hand side, the syntax is exactly the same as a type assertion used anywhere else:

declare const user: string;
declare const req: Request

(req as AuthenticationRequest).user = user;

interface AuthenticationRequest extends Request {
    user: string;
}