如何扩展Opine(DENO框架)中的响应?
这里的第一个问题。
有谁知道如何扩展Opine(DENO框架)中的响应,以便我可以创建自定义响应?
例如,我想创建:
res.success(message)
这样我就不需要每次设置HTTP代码:
res.setStatus(200).json({data: "success" });
我尝试像在此处完成的响应扩展: https://deno.land/x/ [email  prectioned] /span>/test/test/units/app.response.test.test.ts.ts
这是我的代码:
import { opine } from "https://deno.land/x/[email protected]/mod.ts";
const app = opine();
(app.response as any).shout = function (str: string) {
this.send(str.toUpperCase());
};
app.get("/", (req, res) => {
res.shout("hello")
})
app.listen(3000);
console.log("Opine started on port 3000");
export { app };
但是这 是我的代码:我得到的程序:
error: TS2339 [ERROR]: Property 'shout' does not exist on type 'OpineResponse<any>'.
res.shout("hello")
~~~~~
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有真正的“干净”方法,而无需分叉opine并修改库核心的功能和方法。
您可以通过在调用站点上断言类型来满足编译器(例如通过使用
任何
,就像您链接到的测试文件中的任何一样)。另一种方法是使用喜欢在下面的代码的示例重构中:so-71990454.ts
:您可以看到该类型检查模块不会产生任何诊断错误:
There's not really a "clean" way of doing this without forking opine and modifying the functions and methods which are core to the library.
You can satisfy the compiler by asserting the types at the invocation sites (e.g. by using
any
just like in the test file to which you linked). Another approach is to use an assertion function like in the example refactor of your code below:so-71990454.ts
:You can see that type-checking the module produces no diagnostic errors: