访问输入的快速回复

时间:2019-02-26 11:11:49

标签: typescript typescript3.0

我正在尝试像这样扩展express Response类型:

class Registration {
  public static register(express: Application) {
    express.response.someFunction = function () {
      ...
    };
  }
}

但我收到此Typescript错误:

Property 'response' does not exist on type 'Application'.

我必须使用哪种类型来代替Application

1 个答案:

答案 0 :(得分:0)

您可以使用扩充来扩展Response提供的express接口。 Application没有response属性,您必须添加一个中间件函数才能将该函数添加到每个请求中:

declare global {
    namespace Express {
        interface Response {
            someFunction(): string
        }
    }
}

class Registration {
    public static register(express: Application) {
        express.use((req, res, next) => {
            res.someFunction = function () {
                return "foo"
            };
        });
    };

}
Registration.register(app);

app.get("/", (req, res) => {
    res.someFunction();
    res.send({
        test: res.someFunction()
    })
})