Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js typescript和expressjs。更改res json`Response`类型_Node.js_Typescript_Express_Type Declaration - Fatal编程技术网

Node.js typescript和expressjs。更改res json`Response`类型

Node.js typescript和expressjs。更改res json`Response`类型,node.js,typescript,express,type-declaration,Node.js,Typescript,Express,Type Declaration,在typescript中,我试图覆盖express的响应json对象,使其成为始终要使用的特定类型的对象 例如,我想强制执行一个接口类型,如果不遵循以下格式,该接口类型将出错 return res.status(200).json({ data: ["a", {"a": "b"}], success: true, }); 我试图使用dtsgen--m express-f src/types/express.d.

在typescript中,我试图覆盖express的
响应
json
对象,使其成为始终要使用的特定类型的对象

例如,我想强制执行一个接口类型,如果不遵循以下格式,该接口类型将出错

  return res.status(200).json({
    data: ["a", {"a": "b"}],
    success: true,
  });
我试图使用
dtsgen--m express-f src/types/express.d.ts
创建要修改的声明文件,但最终失败

有没有办法覆盖现有库中的特定类型,或者我需要创建一个特定于我需要的声明文件?

interface Json{
interface Json {
  success: boolean;
  data: any[];
}

type Send<T = Response> = (body?: Json) => T;

interface CustomResponse extends Response {
  json: Send<this>;
}
成功:布尔; 数据:任何[]; } 输入Send=(body?:Json)=>T; 接口CustomResponse扩展了响应{ json:Send; }

我能够创建一个新的接口来扩展它。只是需要多学一点:)希望这能帮助其他人

您可以在
req
res
对象的通用类型中设置自定义类型,例如:

将类型*从“express”导入为E;
接口CustomResponseType{
测试:字符串;
}
导出默认异步函数示例(
请求:即请求,
决议:E.答复
):承诺{
返回res.status(200).json({test:'success'});
}

missed然后添加到
export-const-example=asynchHandler(异步(请求:请求,回复:CustomResponse,下一步:下一步功能)=>{
express
因不可键入而臭名昭著。如果您选择继续使用此库,最好避免使用大量自定义中间件,并将类型良好的代码与
express
路由代码分开。很高兴知道,谢谢!