【问题标题】:Declaration merging with custom interface with typescript声明与带有 typescript 的自定义接口合并
【发布时间】:2017-08-14 22:35:15
【问题描述】:

我希望向 express.Request 类型添加一个用户属性,以便 req.user 属于我的自定义类型 IUser。我读到声明合并是要走的路,所以我创建了一个 custom.d.ts 文件

declare namespace Express {
     export interface Request {
         user?: IUser;
     }
}

虽然 typescript 现在允许我使用 req.user,但它被定义为类型 any。在我的打字文件中导入 IUser 也没有帮助,因为它只会让打字稿变得更糟,现在根本无法识别 req.user。 IDE 如何将我的输入视为 IUser?

【问题讨论】:

    标签: node.js typescript express middleware


    【解决方案1】:

    首先,不要一直扩展Express Request,因为并非一直如此!您只需要在特定的路由中更改请求接口。

    其次,不要使用可选字段?,因为它一旦被批准就不是可选的(我猜)

    您所要做的就是使用您的附加字段扩展Express Request,并在您的路线上对其进行注释。像这样:

    interface IMyReq extends Request {
      user: IUser;
    }
    
    app.post('/api/users-list', (req: IMyReq, res) => {
     // Look ma a request with an authenticated user!
    });
    

    【讨论】:

    • 按预期工作!不知道为什么我没想到!
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多