首页 > 解决方案 > 如何使用类型推断正确地为`express.Response`进行声明合并

问题描述

我正在尝试更改声明Response.locals以实现额外的类型安全性。在回答了类似问题之后,我在我的项目中添加了以下内容index.d.ts

import * as express from "express";

interface Locals {
  someData: string
}

declare module "express" {
  export interface Response {
    locals: Locals;
  }
}

如下使用时效果很好:

app.post("/somePath", (req, res: express.Response) => {
  // res.locals has type `Locals` here
});

但是,如果我省略显式说明 的类型,编译res器似乎会推断出不同的类型ResponseResponse.localsany

app.post("/somePath", (req, res) => {
  // oops, res.locals has type `any` here
});

我最初想通过使用 Typescript 来避免拼写错误(比如somedata代替)。someData

Response我对界面的扩充有什么问题?

标签: typescriptexpresstype-inference

解决方案


推荐阅读