【问题标题】:How to change properties of express function如何更改 express 函数的属性
【发布时间】:2021-02-11 21:11:31
【问题描述】:

在 express Request.send 函数中,send 函数接受的基本输入类型在 VS Code 中表示为 (property) Response<any>.send: (body?: any) => Response<any>。我可以将此功能从any 更改为另一种类型吗?我想这样做,所以我可以强迫自己在每个端点上只向前端发送一个特定的 JSON 对象

【问题讨论】:

    标签: node.js typescript express types


    【解决方案1】:

    您可以扩展原始 res 参数来创建您需要的参数:

    type ArgumentsType<T extends (...args: any[]) => any> = T extends (
      ...args: infer A
    ) => any
      ? A
      : never;
    
    type Args = ArgumentsType<typeof app.get>; // get the arguments of app.get
    type subApplication = Args[1]; // select the second param, the function
    type application = ArgumentsType<subApplication>; // get the argument of the funcion
    type res = application[1]; // select the second param: res
    
    // Extend res and overwrite the original send method
    interface myCustomRes extends res {
      send: (arg: object) => any; // force send to only admit object
    }
    
    app.get("/", function (req, res: myCustomRes) {
      res.send("Hello World!"); // Error because we are using string
      res.send({ message: "Hello World!" }); // Ok because we are using object!
    });
    

    Check the demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2015-05-14
      相关资源
      最近更新 更多