typescript - 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?
解决方案
您可以在左侧有一个类型断言,语法与其他任何地方使用的类型断言完全相同:
declare const user: string;
declare const req: Request
(req as AuthenticationRequest).user = user;
interface AuthenticationRequest extends Request {
user: string;
}
推荐阅读
- google-cloud-platform - Gsuite Windows 管理员和非管理员用户
- sql - 创建大小相等的随机存储桶,行不重复
- azure-blob-storage - 如何使用 PowerShell 将导出的 CSV 文件动态写入 Azure blob 容器?
- web-services - 将简体中文转换为繁体中文的Web服务?
- azure - 用于配置 Azure Function App TLS/SSL“仅 HTTPS”设置的 Az CLI
- reactjs - 无法在 MUI 自动完成中选择自定义选项?
- cassandra - sstableloader 远程批量上传
- devtools - 在不使用开发工具的情况下,我还能如何查看本地托管应用程序的响应能力?
- opengl - 使用 GLFW 执行连续动画
- ios - SwiftUI:使用它拖动底部工作表的 ScrollView