【发布时间】:2019-05-13 14:33:04
【问题描述】:
TypeScript 文档讨论了类型断言,但显然它们只能在表达式中使用,而我需要在赋值的左侧断言变量的类型。
我的具体情况是一个快速中间件,它使用user 属性扩展了req 对象:
app.use(async (req, res, next) => {
// ...
req.user = user; // Property 'user' does not exist on type 'Request'.
// ...
});
我知道我可以重新分配变量,但这似乎有点笨拙:
interface AuthenticationRequest extends Request {
user: string;
}
const myReq = <AuthenticationRequest>req;
myReq = user;
有没有更优雅的方式?
【问题讨论】:
-
(req as AuthenticationRequest).user = user。或者,如果不允许该断言,(req as unknown as AuthenticationRequest).user = user.
标签: typescript