我正在尝试像这样扩展express
Response
类型:
class Registration {
public static register(express: Application) {
express.response.someFunction = function () {
...
};
}
}
但我收到此Typescript错误:
Property 'response' does not exist on type 'Application'.
我必须使用哪种类型来代替Application
?
答案 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()
})
})