【问题标题】:Can I have a type assertion on the left hand side of an assignment in TypeScript?我可以在 TypeScript 的赋值左侧有一个类型断言吗?
【发布时间】: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


【解决方案1】:

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

declare const user: string;
declare const req: Request

(req as AuthenticationRequest).user = user;

interface AuthenticationRequest extends Request {
    user: string;
}

【讨论】:

  • 啊,我试过这个:&lt;AuthenticationRequest&gt;req.user = user;,但由于语法错误而失败,我没想到要尝试使用括号。非常感谢!
  • (&lt;AuthenticationRequest&gt;req).user = user; 应该也能正常工作,你只需要额外的()
  • 我意识到这真的很愚蠢,并且可能特定于 express 中间件产生的问题,但是你不会碰巧能够用不同的类型重新声明变量/函数参数,你会吗? ?
  • @AndrewPeterPrifer 您可以指定要使用的参数类型app.use(async (req: AuthenticationRequest , res, next) =&gt; {,但是否有效取决于您是否打开或关闭了strictFunctionTypes(它会在关闭时工作)
  • 是的,我启用了strictFunctionTypes,但为了这种情况,我犹豫是否要关闭它;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
  • 2019-06-29
  • 2021-04-25
  • 1970-01-01
  • 2022-11-21
  • 2011-02-08
相关资源
最近更新 更多