首页 > 解决方案 > Can I have a type assertion on the left hand side of an assignment in TypeScript?

问题描述

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?

标签: typescript

解决方案


您可以在左侧有一个类型断言,语法与其他任何地方使用的类型断言完全相同:

declare const user: string;
declare const req: Request

(req as AuthenticationRequest).user = user;

interface AuthenticationRequest extends Request {
    user: string;
}

推荐阅读