打字稿和表达js。更改 res json `Response` 类型

typescript and express js. change res json `Response` type

在打字稿中,我试图覆盖快递的 Response json 对象成为始终使用的特定类型的对象

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

  return res.status(200).json({
    data: ["a", {"a": "b"}],
    success: true,
  });

我尝试使用dts-gen --m express -f src/types/express.d.ts创建要修改的声明文件,但以失败告终。

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

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

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

interface CustomResponse extends Response {
  json: Send<this>;
}

我能够创建一个扩展它的新界面。只是需要多学一点 :) 希望这可以帮助其他人!

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

import type * as E from 'express';

interface CustomResponseType {
  test: string;
}

export default async function Example(
  req: E.Request<undefined, CustomResponseType, [CustomReqBodyType?], [CustomReqQueryType?]>,
  res: E.Response<CustomResponseType>
): Promise<E.Response<CustomResponseType, Record<string, any>>> {
  return res.status(200).json({ test: 'success' });
}

只是一个扩展回复,如果你想显式定义回复类型,你可以这样做

// overlap the ResBody = any (from Express module) to the exact type 
// you want in CustomResponse

type Send<ResBody = any, T = Response<ResBody>> = (body?: ResBody) => T;

export interface CustomResponse<T> extends Response {
   json: Send<T, this>
}

然后你可以在控制器函数中导入:

async (req: Request, res: CustomResponse<IUser>, next: NextFunction) =>

您的 res.json() 将严格遵守 IUser 界面。