如何指定 Express 响应返回的类型

Sil*_*l05 4 express typescript

我正在尝试使用 TypeScript 标准化我的express.js Web应用程序中的响应,但我不太确定如何全局设置响应应该是这个接口:

{
  success: boolean,
  data?: any,
  error?: string,
}
Run Code Online (Sandbox Code Playgroud)

现在我只是在写:

async (req: Request, res: Response, next: NextFunction) => {
  try {
    registerResponse = await register(req.body.email, req.body.password);
  } catch (error) {
    return res.json({
      success: false,
      error: error.message,
    });
  }

  return res.json({
    success: true,
    data: {
      message: 'Account registered',
    },
  });
};
Run Code Online (Sandbox Code Playgroud)

有没有办法设置其他设置或重写 typedef 来实现硬编码的 res.json 类型?

Tit*_*mir 5

您无法删除在类型上定义的函数,我们可以json通过模块增强为该函数添加重载,但这没什么用,因为如果我们得到错误的属性,编译器将选择该函数的原始版本允许任何。

更激进的方法是创建一个与Response但兼容的新类型,它删除原始json方法并用类型化版本替换它。我们可以使用映射类型,这样我们就不会重复任何原始类型:

// Helpers
type Diff<T extends string, U extends string> = ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;

// Generic typed response, we omit 'json' and we add a new json method with the desired parameter type
type TypedResponse<T> = Omit<Response, 'json'> & { json(data: T): Response };
// An example of a typed response
type AppResponse = TypedResponse<{
    success: boolean,
    data?: any,
    error?: string,
}>

app.get('/', async (req: Request, res: AppResponse, next: NextFunction) => {
    try {
        // ....
    } catch (error) {

        return res.json({
            success: false,
            error: error.message,
            errors: "" // causses error
        });
    }

    return res.json({
        success: true,
        data: {
            message: 'Account registered',
        },
    });

}
Run Code Online (Sandbox Code Playgroud)

不幸的是,没有办法强制开发人员使用通用版本(除了长棍),但通过代码审查,这可能对您来说足够有效。