【问题标题】:avoid using any in the expressjs + typescript避免在 expressjs + typescript 中使用 any
【发布时间】:2022-01-17 12:07:36
【问题描述】:

我在 node/express/typescript 中有一个方法,像这样:

// eslint-disable-next-line
export const errorConverter = (err: any, req: any, res: any, next: any) => {
  let error = err
  if (!(error instanceof ApiError)) {
    const statusCode =
      error.statusCode || error instanceof mongoose.Error ? httpStatus.BAD_REQUEST : httpStatus.INTERNAL_SERVER_ERROR
    const message = error.message || httpStatus[statusCode]
    error = new ApiError(statusCode, message as string, true, err.stack)
  }
  next(error)
}

并像这样使用它app.use(errorConverter)

如何避免在参数中使用any,我可以在那里使用什么类型。需要一些帮助。

【问题讨论】:

  • 你可以使用unknown
  • @about14sheep,如果我给出错误:未知,在 error.statusCode 中出现问题

标签: node.js typescript express


【解决方案1】:

安装express所需的类型

npm i -D @types/express

现在导入 express 的接口

import express, { Request, Response, NextFunction } from "express"

并像这样分配:

const errorConverter = (
    req: express.Request,
    res: express.Response,
    nxt:express.NextFunction) => {
        // your logic here
})

const errorConverter = (
    req: Request,
    res: Response,
    nxt: NextFunction) => {
        // your logic here
})

【讨论】:

  • 谢谢先生,知道如何为错误添加类型。
猜你喜欢
  • 1970-01-01
  • 2020-11-13
  • 2023-01-25
  • 1970-01-01
  • 2020-01-01
  • 2021-06-11
  • 2020-03-02
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多